[英]childNodes property giving incorrect results?
我試圖學習有關DOM的更多信息,並一直在編寫一些遍歷腳本。 我提出的算法在部分工作中效果很好,但是當我將其應用於HTML文檔的整個主體時,它就變得混亂了。 這是HTML:
<!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>
和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());
現在,當我將document.getElementById('wrapper')
傳遞給遍歷函數時,此設置將正常工作,但是當我將其保留為使用document.body
它僅獲得兩個script
元素。 我在Chrome 20.0.1132.34,Firefox 11.0和IE 9上進行了測試,它們都具有相同的結果。 通過測試,我確實發現算法沒有傳遞任何東西, document.body
上的childNodes
屬性的長度為10,當我將其轉換為數組並警告其輸出為text,div,text,div,text時,div,文本,腳本,文本,腳本。 你們誰能解釋為什么childNodes
不選擇最后兩個腳本標簽? 謝謝!
在您調用遍歷腳本時,其他兩個腳本尚不存在。 domready上遍歷遍歷。
document.addEventListener('DOMContentLoaded', function () {
console.log(Traverse());
}, false);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.