为什么我得到的错误无法读取null的属性childNodes?此代码可在24小时内从SAMS Teach Yourself Javascript一书中获取。
<!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>
答案 0 :(得分:7)
您的代码需要在页面完全加载后执行。您可以使用onload事件执行此操作。
您的脚本已添加到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>
答案 1 :(得分:2)
在创建DOM之前执行JavaScript函数。在body标记结束之前包括脚本标记。
您的代码:
<head>
<script></script>
</head>
<body>
</body>
正确的方式:
<head>
// Not here
</head>
<body>
<!-- right before <body> tag is closed -->
<script></script>
</body>
答案 2 :(得分:1)
因为,当执行JS时,您的DOM对象尚未创建。所以把你的脚本放在身体后面。
</body>
<script>
//---your JS code---
</script>
</html>