简体   繁体   English

window.onload 并非一直有效。 为什么

[英]window.onload doesn't work all the time. Why

I've been working on changing the src attribute to change the image in javascript.我一直在努力更改 src 属性以更改 javascript 中的图像。 I was using window.onload = function() and my code wasn't working.我正在使用window.onload = function()并且我的代码不起作用。 I decided to take out window.onload and miraculously my code worked.我决定取出window.onload并且奇迹般地我的代码工作了。 The src attribute changed the image on the page. src属性更改了页面上的图像。

A lot of literature I read boasted about window.onload function as though it was absolutely necessary to load a web page in order for other code to work.我读过的很多文献都吹嘘 window.onload function 好像绝对有必要加载 web 页面才能使其他代码正常工作。 I'm confused because it didn't work for me in this instance.我很困惑,因为在这种情况下它对我不起作用。 And I recalled a recent college assignment I was working on that didn't work with window.onload function.我回想起我最近正在处理的一项大学作业,该作业不适用于 window.onload function。 Here is the script I used with and without window.onload function.这是我使用和不使用 window.onload function 的脚本。 Can somebody give me an explanation for this oddity.有人能给我解释一下这个奇怪的地方吗?

  window.onload = function(){
  function myFunction(){
  document.getElementById("myImg").src = "people5.png";
  };
  };
  </script>
  </head>
 <body>
 <img id = "myImg" src="people1.png" width="240" height="240" alt="logo"/>
 <button onclick="myFunction()">Click me</button>

Now without window.onload现在没有 window.onload

  function myFunction(){
  document.getElementById("myImg").src = "people5.png";
  };

 </script>
 </head>
 <body>
 <img id = "myImg" src="people1.png" width="240" height="240" alt="logo"/>
 <button onclick="myFunction()">Click me</button>
window.onload = function(){
  function myFunction(){
  document.getElementById("myImg").src = "people5.png";
  };
};

myFunction() in window.onload is local to the anonymous function.when you declare myFunction outside window.onload , it is defined in global scope and is therefore accessible to onclick event myFunction()window.onload是本地的声明匿名功能。当myFunction外面window.onload ,它在全球范围内被定义,因此可访问onclick事件

  function myFunction(){
      document.getElementById("myImg").src = "people5.png";
    };
    window.onload = myFunction;

or 要么

 <body onload='myFunction()' >

In this case it is the best to use event lister so you don't overwrite onload function.在这种情况下,最好使用事件列表器,这样您就不会覆盖 onload function。

    window.addEventListener('load', (event) => {
        console.log('page is fully loaded1');
    });

    window.addEventListener('load', (event) => {
        console.log('page is fully loaded2');
    });

https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM