大神們求解答啊!為什么是這樣的?遍歷節點出問題了!
<!DOCTYPE?HTML> <html> <head> ????<meta?http-equiv="Content-Type"?content="text/html;?charset=utf-8"> ????<title>節點屬性</title> </head> <body> <ul> ????<li>javascript</li> ????<li>HTML/CSS</li> ????<li>jQuery</li> </ul> <script?type="text/javascript"> ????node?=?document.getElementsByTagName("li"); ????var?type?=?['元素','屬性','文本',,,,,'注釋','文檔']; ????document.write("節點的數量為:"+node.length+"<br>"); ????for?(var?i?in?node){ ????????each?=?node[i]; ????????document.write("節點名稱:"+each.nodeName+"\t\t"); ????????document.write("節點屬性:"+each.nodeValue+"\t\t"); ????????document.write("節點類型:"+type[each.nodeType]+"<br>") ????} </script> </body> </html>
輸出顯示節點數是三個,但是后面遍歷節點的時候結果是這樣的:
后面那三行是怎么回事啊啊啊啊!!!
2022-03-25
你的代碼里寫了兩遍window.onload!!!!!!!!!!!!!!!!!!
2016-10-23
自問自答一波,剛剛問了另外的大神 : getElement方法返回的是HTMLCollection對象,并不是普通的數組;for/in循環遍歷HTMLCollection對象的屬性,所以才會出現返回undefined值得情況.用普通的for循環就行.
stackoverflow上有人做了詳細的解釋:
http://stackoverflow.com/questions/22754315/foreach-loop-for-htmlcollection-elements
2016-10-23
我覺得可能是循環的問題,因為js的數組是可以隨意擴大的,所以你試試for(var i=0;i<node.length;i++)