Why does only the newest button work? I found that the other function of the onclick button is zero.

function B(sName) {
    this.name = sName;
}
B.prototype = {
    instanceCreatButtonCount: 0,
    funA: function () { // alert instance name
        alert(this.name);
    },
    funB: function () { // create a button which clikced can alert this instance 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();
}
  • After I press divB1, I create a button through b1.funB ().

  • After I press divB2, I create a througb b2.funB () button.

Why only the latest name of the alert button? I found that the other onclick function of the button is null.

+5
source share
1 answer

When you use a.innerHTML += strto add a new element, the entire subtree ais deleted before adding new elements; deleting also cancels any events that you added earlier.

It is better to use the proper DOM functions in this case, i.e. var btn = document.createElement()etc., and a.appendChild(btn).

, @ShadowWizard: http://jsfiddle.net/qR6e8/

+4

All Articles