简体   繁体   中英

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

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

<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. 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 .

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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