關(guān)于removechild清除的次數(shù)問題
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>無標(biāo)題文檔</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");
? // 在此完成該函數(shù)
? ?var cc=content.childNodes;
? ? for(var i=0;i<cc.length;i++)
? ? {x=content.removeChild(cc[i]);
? ? ?x=null;}
}
</script>
<button onclick="clearText()">清除節(jié)點(diǎn)內(nèi)容</button>
</body>
</html>
?為什么我這個(gè)清除分了三次才清除完
?我尋找 子類元素是一次就尋找完的,不知道為什么
2016-08-10
原因我不知道,但是倒過來,寫成i--的就可以一次清除了
2016-08-09
這是因?yàn)槊看吻宄?jié)點(diǎn)時(shí)childNodes的長(zhǎng)度(即tt.length)都縮短1,而每次I增大1,這樣會(huì)導(dǎo)致i的值還沒有達(dá)到最初的tt.length時(shí)循環(huán)會(huì)比提前結(jié)束;
2016-08-09
在for循環(huán)里面,加上
if(otest[i].nodeType!=1){
? ? ? ? ?continue; ?
? ? ? }
? ? ? else{
? ? ? ? var x=content.removeChild(otest[i]); ?
? ? ? } 試試,具體原因,不是很懂