刪除節點的問題
<!DOCTYPE?HTML> <html> <head> <meta?http-equiv="Content-Type"?content="text/html;?charset=utf-8"> <title>無標題文檔</title> </head> <body> <div?id="content"> ??<h1>html</h1> ??<h1>php</h1> ??<h1>javascript</h1> ??<h1>jquery</h1> ??<h1>java</h1> </div> <script?type="text/javascript"> function?clearText()?{ ??var?content=document.getElementById("content"); ??//?在此完成該函數 ????//for(var?i=0;i<=content.childNodes.length;i++){ ????????var?x=content.removeChild(content.childNodes[0]); ????????x=null; ????//} ???????? ???????? ????//} ?? ?? } </script> <button?onclick="clearText()">清除節點內容</button> </body> </html>
為什么要點兩下才能觸發事件
2016-12-14
因為存在空白節點,content的第0個子節點是空白節點。如果用document.write(content.childNodes.length);來檢驗一下,就明白了??瓷先ソY果應該是6,但實際結果是11.
2016-12-11
第一下沒反應的是刪除的空白節點。
你這樣寫一行的話,就沒有空白節點了。