[英]Why this DOM traversal is not working?
我編寫了一個非常簡單的JavaScript腳本來遍歷頁面的DOM。 這是整頁:
<html>
<head>
<title>DOM Traversal</title>
<script>
// Traversing the DOM tree
"use strict";
//var node = document.documentElement; //works
var node = document.body; // does not work
while(node) {
console.log(node);
node = node.lastChild;
}
</script>
</head>
<body>
<h1>Sample H1</h1>
<div id="text">
<p>Sample paragraph</p>
</div>
</body>
</html>
正如您在注釋中看到的那樣,當我將node
設置為document.documentElement
,遍歷有效,但對document.body
無效。 這是為什么? 順便說一下,我在Chrome 35.0.xxxx上。
使用純JavaScript嘗試此解決方案
工作提琴: http : //jsfiddle.net/beU8F/3/
// Traversing the DOM tree
function domReady () {
//var node = document.documentElement; //works
var node = document.body; // does not work
while(node) {
console.log(node);
node = node.lastChild;
}
}
if ( document.addEventListener ) {
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false);
domReady();
}, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
domReady();
}
});
}
'dom'還沒有准備好; 像這樣使用jQuery:
$(document).ready(function() {
//var node = document.documentElement; //works
var node = document.body; // does not work
while(node) {
console.log(node);
node = node.lastChild;
}
});
我假設您可以使用jQuery。 如果不是,您需要找到jQuery.ready的替代方法。 看到這個鏈接 。
<html>
<head>
<title>DOM Traversal</title>
<script>
function foo(){
// Traversing the DOM tree
"use strict";
//var node = document.documentElement; //works
var node = document.body; // does not work
while(node) {
console.log(node);
node = node.lastChild;
}
}
</script>
</head>
<body onLoad="javascript: foo();">
<h1>Sample H1</h1>
<div id="text">
<p>Sample paragraph</p>
</div>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.