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