This is simplified code that demonstrates my issue:
class TestClass {
constructor(label) {
this.uid = Math.floor(Math.random() * 1000);
this.label = label;
this.btnId = "btn-" + this.uid;
let tableBody = document.getElementById("the-table").innerHTML;
tableBody += `<tr><td id=${this.uid}><button id=${this.btnId}>${this.label}</button></td></tr>`
document.getElementById("the-table").innerHTML = tableBody;
document.getElementById(this.btnId).onclick = function() {
incr();
}
}
}
let a = new TestClass("+1");
let b = new TestClass("+1");
let c = new TestClass("+1");
let x = 1;
function incr() {
x += 1;
console.log(x);
}
When I run it in browser, only the button/class to last assigned variable ("c" in this case) works, other buttons do nothing. I guess I am missing something obvious...
I am interested in solution with vanilla JS. I saw similar question which was solved with jQuery "on" method, but I did not test it.