路由到新页面时加载不起作用

onload not working when routing to a new page

本文关键字:加载 不起作用 新页面 路由      更新时间:2023-09-26

假设我在网站的"主页"页面。现在,当我从主页本身单击"关于我们"链接时,我想更改"关于我们"页面上DIV元素的位置。但是下面的代码没有任何反应。

//HTML Code of Home page
<html>
<head></head>
<body>
<a href="AboutUs.html" onclick="NavTo();">About Us</a>
<script type="text/javascript" src="Scripts/javascript code.js"></script>
</body>
</html>
//javascript code.js
function NavTo() {
    document.getElementById("OurServices").onload = function() {
        alert("hello");
        document.getElementById("OurServices").style.position = "fixed";
    }
}

我已经放置了"警报"代码,以便我了解该函数中是否正在执行某些内容。但是没有显示警报,这意味着该函数未执行。我在这里做错了什么?

您需要将警报代码放入 AboutUs.html 文件中。

这是因为在

js 文件运行时页面已经加载。

  1. 一个好的做法是将外部 js 文件引用放在 html 文件中 body 标记的末尾之前。

  2. 并且还请确保html格式正确,请不要将"head"标签放入"body"标签中。

  3. 此外,您还需要删除 onload 事件触发器,因为该事件实际上不是由 onload 触发的,而是通过单击触发的。

因此,为了使您的页面正常工作,js文件应该如下所示:

function NavTo(){
     alert("hello");
 }; 

您的 html 文件应如下所示:

    //HTML Code of Home page
   <html>
     <head></head>
     <body>
       <a href="AboutUs.html" onclick="NavTo();">About Us</a>
       <script type="text/javascript" src="Scripts/javascript code.js"></script>
     </body>
   </html>

希望这能有所帮助。

@Peter Hearly:非常感谢你的回答。下面是确切的代码:

//HTML Code of Home page
<html>
<head></head>
<body>
<a href="AboutUs.html?section=OurServices">About Us</a>
<script type="text/javascript" src="Scripts/javascript code.js"></script>
</body>
</html>
//HTML Code of About Us page
<html>
<head></head>
<body onload="NavTo(document.URL);">
<script type="text/javascript" src="Scripts/javascript code.js"></script>
</body>
</html>
//javascript code.js
function NavTo() {
var eqPosition = pageURL.indexOf("=");  //get the position number of "=" sign
var html_id = pageURL.substring(eqPosition+1,pageURL.length);  //get the string to the right side of the "=" sign
//few lines of required code
}