點擊兩次才刪除一個節點問題
<!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");
??//?在此完成該函數
??var?o?=?document.getElementsByTagName('h1');
??var?i=0
??for(i?=?0;?i<o.length;?i--){
??????content.removeChild(content.childNodes[i]);
??}
}
</script>
<button?onclick="clearText()">清除節點內容</button>
</body>
</html>為什么我這是點兩下才刪除一個節點呢,哪位大神幫忙解答下
2015-07-15
childNodes不只是h1等node節點還有你標簽的換行回車等文本節點.如果只想刪除node節點.建議替換為content.children[i],或者在循環時判斷其nodeType==1
2015-07-15
<!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> ? ? <button?onclick="clearText()">清除節點內容</button> ? ?<script?type="text/javascript"> function?clearText()?{ ??var?content=document.getElementById("content"); ??//?在此完成該函數 ??var?a?=?content.childNodes.length; ??for(var?i?=?0;?i<a;?i++){ ??????content.removeChild(content.childNodes[0]); ??} } </script> ? </body> </html>