Javascript childNodes属性是否给出不正确的结果?
我正在努力学习更多关于DOM的知识,并一直在编写一些遍历脚本。我提出的算法在我所做的部分工作中运行良好,但当我将其应用于HTML文档的整个主体时,它变得混乱。以下是HTML:Javascript childNodes属性是否给出不正确的结果?,javascript,dom,Javascript,Dom,我正在努力学习更多关于DOM的知识,并一直在编写一些遍历脚本。我提出的算法在我所做的部分工作中运行良好,但当我将其应用于HTML文档的整个主体时,它变得混乱。以下是HTML: <!DOCTYPE html> <html lang='en'> <head> <meta charset='utf-8' /> <title>Lumen Tests</title> <li
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Lumen Tests</title>
<link rel='stylesheet' href='../../qunit/qunit.css' />
</head>
<body>
<div id='qunit'></div>
<div id='qunit-fixture'></div>
<div id='wrapper'>
<div id='header'></div>
<div id='content'>
<p id='para'>Lorem ipsum dolor sit amet.</p>
</div>
<div id='footer'></div>
</div>
<script src='../../qunit/qunit.js'></script>
<script src='../lib/traverse.js'></script>
<script src='../lib/lumen.js'></script>
<script src='features.js'></script>
</body>
</html>
流明试验
Lorem ipsum door sit amet
还有JavaScript:
(function () {
'use strict';
function toArray(list) {
var array = [],
len = list.length,
i = 0;
while (i < len) {
array[i] = list[i];
i += 1;
}
return array;
}
function Traverse() {
var that = this;
this.allTags = function (node) {
var context = node || document.body,
children = [],
array = [],
len,
i = 0;
children = toArray(context.childNodes);
len = children.length;
while (i < len) {
if (children[i].nodeType === 1) {
array.push(children[i]);
array = array.concat(that.allTags(children[i]));
}
i += 1;
}
return array;
};
}
var foo = new Traverse();
window.Traverse = foo.allTags;
}());
alert(Traverse());
(函数(){
"严格使用",;
函数toArray(列表){
变量数组=[],
len=list.length,
i=0;
而(我
现在,当我将
document.getElementById('wrapper')
传递给遍历函数时,这个设置会很好地工作,但是当我将它留给使用document.body
时,它只会获取两个脚本
元素。我在Chrome 20.0.1132.34、Firefox 11.0和IE 9上进行了测试,结果都是一样的。通过测试,我确实发现算法没有任何错误,document.body
上的childNodes
属性给出了10的长度,当我将其转换为数组并向其发出警报时,输出为text,div,text,div,text,div,text,script,text,script。你们能解释一下为什么childNodes
没有拾取最后两个脚本标记吗?谢谢大家! 调用遍历脚本时,其他两个脚本还不存在。在domready上调用traverse
document.addEventListener('DOMContentLoaded', function () {
console.log(Traverse());
}, false);
这段代码是用什么脚本编写的
traverse.js
?@Mattmald毫无疑问,很好的先生。您的代码在其他两个脚本被解析之前就已经运行了。将遍历
脚本放在
元素的结束标记之前将解决此问题,而无需“需要”花哨的事件。谢谢,现在看起来很明显。我不应该一大早就试图解决这个问题。除息的