2014-02-17 24 views
0

我认为“document.documentElement.cildNodes”是标签所有的childNodes和以前一样,但今天我做我的代码excrise,我发现一个特殊情况:javascript为什么“document.documentElement.childNodes”输出不同的结果?

<!DOCTYPE html> 
<html> 
<head> 
<title>javascript</title> 
<script> 
    var o = document.createElement('script'); 
    o.text = 'alert("111")'; 
    var ohtml = document.documentElement; 
    alert(ohtml.nodeName); //output HTML 
     alert(ohtml.childNodes.length); //nodes length is 1 
    alert(ohtml.childNodes.length); //just head 
    ohtml.childNodes[0].appendChild(o); 
    function shownode() { 
     var ohtml = document.documentElement; 
     alert(ohtml.nodeName); 
     alert(ohtml.childNodes.length); //nodes length is 3 
     alert(ohtml.childNodes[0].nodeName); //head 
     alert(ohtml.childNodes[1].nodeName); //#text 
       alert(ohtml.childNodes[2].nodeName); //body 
    } 
</script> 
</head> 
<body><div>test</div><input id="Button1" type="button" value="show nodes" onclick="shownode();" /> 
</body> 
</html> 

为什么我EXCUTE“document.documentElement.childNodes”在标签中的标签和功能会得到不同的结果? 我希望有人能给我更多关于这个的例子。非常感谢!

回答

3

问题是,你在头脚本标记中这样做,所以当它被执行时,整个DOM还没有被加载到页面中。而当你在控制台中调用该函数的情况下,DOM完全加载,以确保这一点,你可以将所有的代码到window.onload事件,像这样:

window.addEventListener("load", function() { 
    var o = document.createElement('script'); 
    o.text = 'alert("111")'; 
    var ohtml = document.documentElement; 
    alert(ohtml.nodeName); //output HTML 
    alert(ohtml.childNodes.length); //nodes length is not 1 
    alert(ohtml.childNodes.length); // not just head 
    ohtml.childNodes[0].appendChild(o); 
}); 

,如果你不不想使用window.onload事件,只需将其放入您的身体标记中:

<body> 
<!--your stuff--> 
<script> 
    alert(ohtml.nodeName); //output HTML 
    alert(ohtml.childNodes.length); //nodes length is not 1 
    alert(ohtml.childNodes.length); // not just head 
</script> 
</body> 
相关问题