求指點感激不盡
<!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">
var content=document.getElementById("content");
var nodetemp=content.childNodes;
? // 在此完成該函數(shù)
? //document.write(nodetemp[1]);
? /*document.write("還未刪除之前子節(jié)點數(shù)組的長度為:"+nodetemp.length+"<br>");
? ? for(var j=0;j<nodetemp.length;j++){
? ? ? ? document.write(nodetemp[j].nodeType+"-"+nodetemp[j].nodeValue+"-"+nodetemp[j].innerHTML+"<br>");
? ? }*/
function clearText() {
? ? var i=0;
? ? while(i<nodetemp.length){
? ? ? ? if(nodetemp[i].nodeType==3){
? ? ? ? ? ? i++;
? ? ? ? }else{
? ? ? ? ? ? content.removeChild(nodetemp[i]);?
? ? ? ? ? ? i=i+1;
? ? ? ? }?
? ? }
}
? ? /*document.write("此時子節(jié)點數(shù)組的長度為:"+nodetemp.length+"<br>");
? ? for(var z=0;z<nodetemp.length;z++){
? ? document.write(nodetemp[z].nodeType+"-"+nodetemp[z].nodeValue+"-"+nodetemp[z].innerHTML+"<br>");*/
? ??
</script>
<button onclick="clearText()">清除節(jié)點內(nèi)容</button>
</body>
</html>
求指點,不知道自己這樣子寫對不對,雖然已經(jīng)將節(jié)點類型為元素--1的節(jié)點都刪了。
2018-08-24
你這段代碼可以達到目的,但如果你把if語句注釋掉,就會出現(xiàn)BUG,刪除結(jié)點應該從后往前刪,因為從前面刪除之后后面節(jié)點的索引值會變化.