为什么只能使用最新的按钮?我发现其他按钮的onclick函数为null

acj*_*ren 5 javascript

function B(sName) {
    this.name = sName;
}
B.prototype = {
    instanceCreatButtonCount: 0,
    funA: function () { // alert instance's name
        alert(this.name);
    },
    funB: function () { // create a button which clikced can alert this instance's name through funA;
        var that = this;
        B.prototype.instanceCreatButtonCount++;
        var id = "_id" + that.instanceCreatButtonCount;
        var str = "<button id='" + id + "' >clike me</button>";
        var a = document.getElementById("btns");
        a.innerHTML += str;
        var btn = document.getElementById(id);
        btn.onclick = function () {
            that.funA();
        };
    }
};
var b1 = new B("Jim");
var divB1 = document.getElementById("b1");
divB1.onclick = function () {
    b1.funB();
}
var b2 = new B("Dad");
var divB2 = document.getElementById("b2");
divB2.onclick = function () {
    b2.funB();
}
Run Code Online (Sandbox Code Playgroud)
  • 单击divB1后,我通过b1.funB()创建一个按钮.

  • 单击divB2后,我通过b2.funB()创建一个按钮.

为什么只有最新的按钮警报名称?我发现其他按钮的onclick函数为null.

Ja͢*_*͢ck 4

当您使用附加新元素时,在再次添加新元素之前,a.innerHTML += str整个子树都会被删除;a删除还会解除您之前添加的任何事件的绑定。

在这种情况下,最好使用适当的 DOM 函数,即var btn = document.createElement()、 等和a.appendChild(btn)

@ShadowWizard 提供的小提琴:http://jsfiddle.net/qR6e8/