简体   繁体   English

外部javascript window.onload提前触发

[英]External javascript window.onload firing early

I have a page that references an external javascript file, and when I tell it run a function onload, it is giving me errors (I assume because it is firing before the page is loaded.) "Cannot set property 'innerHTML' of null" 我有一个页面引用了一个外部javascript文件,当我告诉它运行一个函数onload时,它给了我错误(我认为是因为它是在加载页面之前触发的。)“无法将属性'innerHTML'设置为null”

What do I need to do here to fire run() after the page is loaded? 页面加载后,我需要在这里执行什么操作来触发run()?

HTML HTML

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript" src="js/test.js"></script>
</head>
<body>
    <div id="test"></div>
</body>
</html>

JS JS

window.onload = run();

function run() {
    document.getElementById("test").innerHTML = "found it";
}

Try this instead: 尝试以下方法:

window.onload = run

When you do window.onload = run() you are immediately executing run() and assign whatever is returned to the window.onload property. 当您执行window.onload = run()您将立即执行run()并将返回的内容分配给window.onload属性。 This is why it's not working correctly. 这就是为什么它不能正常工作的原因。

It should be: 它应该是:

window.onload = run;

When you do: 当您这样做时:

window.onload = run();

You're actually running the function called run , and then assigning its return-value ( undefined in this case) to window.onload . 您实际上是在运行名为run的函数,然后将其返回值(在这种情况下undefined )分配给window.onload

This function is running before the page even gets loaded (since you are running it explictly by doing run() ), at which time the div with id test doesn't even exist. 该函数在页面加载之前就已经运行(因为您通过run()来显式运行它),此时id testdiv甚至不存在。 This is why you're getting the error. 这就是为什么您得到错误。

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

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