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();
}
Dopo aver fatto clic divB1, ho creare un pulsante attraverso b1.funB().Perché può funzionare solo il pulsante più recente? Trovo che la funzione onclick di altro pulsante è nullo
Dopo aver fatto clic su divB2, creo un pulsante througb b2.funB().
Perché è possibile solo il nome di avviso pulsante più recente? Trovo che la funzione onclick di un altro pulsante sia nullo.
Buona cattura! [Caso di test dal vivo che mostra che funziona] (http://jsfiddle.net/qR6e8/) con la tua correzione. –
@ShadowWizard ringraziamenti per il violino :) –
grazie mille. Ho ignorato "Quando usi a.innerHTML + = str per aggiungere un nuovo elemento, l'intero sottoalbero di a viene rimosso prima che i nuovi elementi vengano aggiunti di nuovo". – acjialiren