【发布时间】:2013-07-17 06:43:52
【问题描述】:
我正在尝试编写一个函数,该函数将遍历我的“主”div 元素的子节点,并将元素标记名称输出到 hmtl 页面上,每次我尝试编译我的代码时,我最终都会得到未定义.任何人都可以解释为什么?
可能是因为 Console.log 返回 undefined 吗?但如果它不应该我仍然从我的 for 循环中接收某种输出?
function looper() { //function that will loop through the child nodes of main
var nodes = document.getElementById('main').childNodes;
for(i=0; i<nodes.length; i++) {
console.log(nodes[i]);
}
}
HTML
<div id ="main">
<h1> Jimms web site </h1>
<nav>
<a href="index.html">Home page</a> |
<a href="about.html">About me</a> |
<a href="contact.html">Contact me</a>
</nav>
<p> This is a list: </p>
<div>
<ol id = "list">
<li><a href="mega">hi</a> - </li>
<li><a href="mario">mario</a> - </li>
<li><a href="luigi">luigi</a> - </li>
<li><a href="mash">mash</a> - </li>
<li><a href="mash">mash</a> - </li></ol>
</div>
<p> Thats it </p>
</div>
looper();
【问题讨论】:
-
首先,我建议使用
.children而不是.childNodes -
这样做后,我的未定义计数从 21 例变为 10 例。但是,我不明白为什么要这样做,我不明白为什么病例下降了。
-
.children仅提供元素,而.childNodes包含不必要的文本节点。 -
在循环之前,添加
console.log(nodes);并检查控制台的值。 -
-- [02:57:01.604] ({0:{}, 1:{}, 2:{}, 3:{}, 4:{}, 5:{}, 6 :{}, 7:{}, 8:{}, 9:{}}) 是我在循环前得到的控制台日志
标签: javascript loops undefined