javascript 无法读取 null 的属性 childNodes
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15199817/
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
Cannot read property childNodes of null
提问by Aaron Chen
Why do I get the error cannot read property childNodes of null? This code is obtained from the book SAMS Teach Yourself Javascript in 24 hours.
为什么我收到错误无法读取 null 的属性 childNodes?这段代码是从《SAMS Teach Yourself Javascript in 24 hours》一书中获得的。
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
<script>
var text = "";
var pElement = document.getElementById("toDoNotes");
for (var i=0; i < pElement.childNodes.length; i++) {
if (pElement.childNodes[i].nodeType ==3){
text += pElement.childNodes[i].nodeValue;
};
}
alert("The paragraph says:\n\n" + text);
</script>
</head>
<body>
<h1>Things To Do</h1>
<ol id="toDoList">
<li>Mow the lawn</li>
<li>Clean the windows</li>
<li>Answer your email</li>
</ol>
<p id="toDoNotes">Make sure all these are completed by 8pm so you can watch the game on TV!</p>
</body>
</html>
回答by Arun P Johny
Your code needs to be executed after the page is completely loaded. You can use the onloadevent to do this.
您的代码需要在页面完全加载后执行。您可以使用onload事件来执行此操作。
Your script is added to the head
element, and this will get executed before the toDoNotes
element is added to the dom. Thus document.getElementById("toDoNotes")
will return a null value.
你的脚本被添加到head
元素中,这将在toDoNotes
元素被添加到 dom之前执行。因此document.getElementById("toDoNotes")
将返回一个空值。
<html>
<head>
<title>To-Do List</title>
<script>
function init(){
var text = "";
var pElement = document.getElementById("toDoNotes");
for (var i=0; i < pElement.childNodes.length; i++) {
if (pElement.childNodes[i].nodeType ==3){
text += pElement.childNodes[i].nodeValue;
};
}
alert("The paragraph says:\n\n" + text);
}
</script>
</head>
<body onload="init()">
<h1>Things To Do</h1>
<ol id="toDoList">
<li>Mow the lawn</li>
<li>Clean the windows</li>
<li>Answer your email</li>
</ol>
<p id="toDoNotes">Make sure all these are completed by 8pm so you can watch the game on TV!</p>
</body>
</html>
回答by silvachathura
The JavaScript function is executed before DOM are created. Include the script tag at the end before body tag ended.
JavaScript 函数在创建 DOM 之前执行。在 body 标记结束之前在末尾包含 script 标记。
YOUR CODE:
你的代码:
<head>
<script></script>
</head>
<body>
</body>
CORRECT WAY:
正确方法:
<head>
// Not here
</head>
<body>
<!-- right before <body> tag is closed -->
<script></script>
</body>
回答by Engineer
Because, when your JS is executed, your DOM objects are not created yet. So put your script after the body.
因为,当你的 JS 被执行时,你的 DOM 对象还没有被创建。所以把你的脚本放在身体之后。
</body>
<script>
//---your JS code---
</script>
</html>