0

直到两天前,当我遇到这个麻烦时,我才认为我对在 js 中添加和删除元素感到满意。

好的,这是我的问题:

我试图动态创建 div,附加到页面上的元素,为我在数组中创建的新 div 添加句柄,然后运行循环并删除数组中的所有 div(来自数组和页面)

这是我创建 div 的代码:

var this_object=this;this.tempdivs=new Array();var thandle='';

var t=document.createElement('div');var br=document.createElement('br');
var txt=document.createTextNode(content_body);
t.appendChild(content);t.appendChild(txt);t.appendChild(br);
thandle=this_object.chat_rec_handle.appendChild(t);
this_object.tempdivs.push(thandle);

this_object.chat_rec_handle是我在创建后附加的位置,它实际上是附加的。

我的问题是什么时候想要删除我创建的 div

    var divlength=this_object.tempdivs.length;
    for(var i = 0; i < divlength; i++)
    {
     var tempobj=this_object.tempdivs[this_object.tempdivs.length-1];
     alert(tempobj.parentNode); 
/* this alert gives me null, does that mean the parent no longer exists? */
     tempobj.parentNode.removeChild(tempobj);
     this_object.tempdivs.pop();
    }

这很令人沮丧,但我知道代码没有错,请问我做错了什么?

4

1 回答 1

0

首先,为什么不直接i用作 div 数组的索引呢?for 循环开始后的第一行应该是:

 var tempobj=this_object.tempdivs[i];

然后你可以删除这一行:

 this_object.tempdivs.pop();

其次,在尝试删除之前,您可能需要检查以确保元素具有父元素(尚未删除):

 tempobj.parentNode && tempobj.parentNode.removeChild(tempobj);

该更改将防止错误发生,但不会解决其原因。你必须找出原因。没有发布任何其他代码,我不能说别的。

于 2010-11-24T05:29:15.677 回答