Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can only newest button work ? I find that other button's onclick function is null

Tags:

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();
}
  • After I click divB1, I create a button through b1.funB().

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

Why can only newest button alert name ? I find that other button's onclick function is null.

like image 773
acjialiren Avatar asked Oct 07 '22 22:10

acjialiren


1 Answers

When you use a.innerHTML += str to append a new element, the entire subtree of a gets removed before the new elements are added again; the removal also unbinds any events you have added before.

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

Fiddle provided by @ShadowWizard: http://jsfiddle.net/qR6e8/

like image 177
Ja͢ck Avatar answered Oct 10 '22 02:10

Ja͢ck