看有的同學是正序循環的解法,求大佬解答
for(var i=0;i<content.childNodes.length;i++){
????? if(content.childNodes[i].nodeType!=1){??
???????? continue;?
????? }else{
???????? content.removeChild(content.childNodes[i]);???
????? }
????????
????? }
這個試了下結果,沒問題,不過有個地方想不明白,這個i<content.childNodes.length,這個?content.childNodes.length不是動態變化的嗎,因為每次刪除一個節點,這個content.childNodes.length就變小了,那豈不是沒法遍歷完所有的節點?比如有四個節點,i=0的時候,content.childNodes.length是4, i=1的時候,content.childNodes.length就是3了, i=2的時候,content.childNodes.length就是2了,循環就沒了,最后的節點壓根沒遍歷到呀。
2019-03-18
for(var i=0;i<content.childNodes.length;i++){
? ? ? if(content.childNodes[i].nodeType!=1){
? document.write("當i為:"+i+" ");
? document.write("長度為:"+content.childNodes.length+"<br>");
? ? ? ? ?continue;??
? ? ? }else{
? ? ? ? ?content.removeChild(content.childNodes[i]);?
document.write("當i為:"+i+" ");
document.write("長度為:"+content.childNodes.length+"<br>");?
? ? ? }
通過這樣輸出,你就可以看出長度是遞減的,i是遞增的,存在空白節點,刪除一個元素節點,空白節點就會頂上位置。這里最后會留下空白節點(本身這里的if判斷就把空白節點留下了)
2019-03-27
可以判斷數組長度,重置i=-1,確保再次循環i=0, 進而刪除所有節點;
for(var i=0;i<childNodes.length;i++){
? ? ? content.removeChild(childNodes[i]);
? ? ? x=null;
? ? ? if(childNodes.length>0){
? ? ? ? ?// alert(i+"長度"+childNodes.length);
? ? ? ? ? i=-1;
? ? ? }
2019-03-25
實現了結果,不知道科學不科學
<!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");
? // 在此完成該函數
? mylength=content.childNodes.length;
? for (var i=1; i<mylength; i++){
? ? content.removeChild(content.childNodes[i]);??
? }
??
}
</script>
<button onclick="clearText()">清除節點內容</button>
</body>
</html>
2019-03-15
你直接試試log就能看出來,如果沒有前面的if條件,實際上是根本遍歷不了所有節點的。如果我猜的沒錯的話,之所以能遍歷,并不是因為i一直是0,而是有空節點,那個length會隔一次減1,不會一直減1.并且如果我這個題目要求的刪除所有的子節點,包括空白節點,那這個答案就是錯的。
2019-03-14
i不會變,i始終是0? 只有content.childNodes.length長度會變