javascript getElementById 和 onLoad

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14157436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:52:18  来源:igfitidea点击:

getElementById and onLoad

javascriptonloadgetelementbyid

提问by Extermiknit

HTML file ...

HTML文件...

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="src/myJS.js"></script>
</head>
<body onload="myJS.myFunction();">
<p id="p01"></p>
</body>
</html>

External Javascript file (called myJS.js for convenience) ...

外部 Javascript 文件(为方便起见称为 myJS.js)...

myJS = {
    myFunction: function()
    {
        //This works
        document.write("Hello world. ");

        //This does not work
        document.getElementById("p01").appendChild(document.createTextNode("Hello world, again"));
    }
};

My best guess is that the node p01has not been created when myJSis executed, but I thought that onloadwould do the right thing with it.

我最好的猜测是该节点p01myJS执行时尚未创建,但我认为这样onload做是正确的。

回答by bfavaretto

If your external js really contains both lines of code you posted, the problem is that document.writeis overwriting the whole HTML (it behaves like that as soon as the DOM is loaded). Then getElementByIdwon't find any #p01, because it won't exist anymore.

如果您的外部 js 确实包含您发布的两行代码,则问题document.write是覆盖整个 HTML(一旦加载 DOM,它的行为就会如此)。然后getElementById将找不到任何#p01,因为它不再存在。

If you simply remove the document.writecall, your code is supposed to work (see a live example).

如果您只是删除document.write调用,您的代码应该可以工作(请参阅现场示例)。

回答by asgoth

Because p01is not yet added to the DOM.

因为p01还没有添加到DOM中。

Try like this:

像这样尝试:

<body>
<p id="p01"></p>
<script type="text/javascript">
window.onload = myJS.myFunction;
</script>
</body>