问题removeChild的许多元素

时间:2014-01-22 17:09:54

标签: javascript html css3 css-animations

我有一个函数,它使用类animate(使用css3动画)创建div,然后在webKitAnimationEnd触发时删除它。当我有多个div时出现问题:该函数只删除第一个div,但是与其他函数一起失败,导致Uncaught TypeError: Cannot call method 'removeChild' of null

function msg(x) {
    cnt = document.getElementsByClassName("animate").length;
    div = document.createElement("div");
    div.textContent = x;
    div.className = "animate";
    div.style.bottom = (cnt) * 30 + "px";
    document.getElementById("wrapper").appendChild(div);
    div.addEventListener("webkitAnimationEnd", function () {
        div.parentNode.removeChild(div);
    });
}

这是一个jsfiddle,我的代码重现了这个问题:http://jsfiddle.net/p5HR3/3/

我怀疑当有很多div时,函数不知道要删除哪个div。我能做什么?提前谢谢。

2 个答案:

答案 0 :(得分:1)

将事件处理程序代码更改为:

this.parentNode.removeChild(this);

在这种情况下,this将指向正确的div,它触发了一个事件。

P.S。:onClick="for(i=0;i<10;i++){msg('message n.'+i);}" - 这很糟糕。不要使用内联Javascript。

答案 1 :(得分:1)

您应该将变量设置为局部变量(在首次使用前使用var),这样它们对于每个函数调用都是唯一的。正如你现在拥有它们一样,它们是全局变量,因此它们都共享一个变量副本,因此只删除了一个div。

实现目标:

function msg(x) {
    var cnt = document.getElementsByClassName("animate").length;
    var div = document.createElement("div");
    div.textContent = x;
    div.className = "animate";
    div.style.bottom = (cnt) * 30 + "px";
    document.getElementById("wrapper").appendChild(div);
    div.addEventListener("webkitAnimationEnd", function () {
        div.parentNode.removeChild(div);
    });
}

仅供参考,像您一样使用的“隐式”全局变量是javascript代码中可怕的错误来源。所有变量都应该显式声明为全局变量或声明为local(最好是local,除非你必须使用全局变量)并且你不会再被这个隐含的全局问题所困扰。


仅供参考,在这种特殊情况下,您也可以通过使用this来引用接收到“webkitAnimationEnd”事件的节点来解决您的问题,但是您仍然不应该使用隐式全局变量,以便也应该清理:

function msg(x) {
    var cnt = document.getElementsByClassName("animate").length;
    var div = document.createElement("div");
    div.textContent = x;
    div.className = "animate";
    div.style.bottom = (cnt) * 30 + "px";
    document.getElementById("wrapper").appendChild(div);
    div.addEventListener("webkitAnimationEnd", function () {
        // the this ptr will contain a reference to the node that
        // received the webkitAnimationEnd event
        this.parentNode.removeChild(div);
    });
}