简体   繁体   English

为什么body onload可以工作,但是window.onload或document.onload不能工作

[英]why does body onload work but window.onload or document.onload NOT work

So I want to hide a div, so I have my code 所以我想隐藏一个div,所以我有我的代码

function hide(){hide div code}

document.onload = hide();

Does not work. 不起作用。

window.onload = hide();

Does not work. 不起作用。

However if I go to the HTML document and write 但是,如果我转到HTML文档并编写

<body onload="hide()"> 

This works. 这可行。

Now I understand that I should not have javascript in the html document, but how do I actually make the javascript WAIT until the entire page has loaded and then execute some code. 现在,我了解到我不应该在html文档中使用javascript,而是如何真正使javascript等待,直到整个页面加载完毕,然后执行一些代码。 I am certain that the code is running before the page has loaded, and I just cant work out why. 我确定代码是在页面加载之前运行的,我无法弄清楚原因。

Do you have any ideas on how I can make this work? 您对我如何进行这项工作有任何想法吗?

To make this work, you have to pass the function itself instead of calling it and passing the value it returns. 要使此工作有效,您必须传递函数本身,而不是调用它并传递它返回的值。

It means you have to write: 这意味着您必须编写:

window.onload = hide;  // Without parentheses.

In passing, note that onload is only supported by window , not document . 顺便说一句 ,请注意onload仅受window支持,而不受document支持。

另外,您可以尝试像这样调用代码:

window.onload = function () { hide(); }

是的,我修复了它,这是另一个JS元素,导致我的功能出现问题!

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

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