Give a function call to multiple Buttons within a FOR-NEXT-Loop (HTML5 Canvas)
Hi!
I try to give a function call to 3 buttons i have on my stage. Each of these Buttons should call the same function but with different parameters:
var _this = this;
cnt = 0;
_this.txt_info.text = "";
for (i = 1; i <= 3; i++) {
_this["but" + i].on('click', function () {
schreibe(i);
});
}
function schreibe(u) {
cnt++;
_this.txt_info.text = "Clicked on button " + u + "\nClick count: " + cnt;
}
The result is strange:
Clicking on a button will call the function, but the parameter is allways 4 - no matter if i click on but1, but2 or but3. Click count works fine and is counting - no matter if i click on but1, but2 or but3.
This will work, but on a later project i have about 20 buttons on my stage and i wont do the following code for each button:
var _this = this;
cnt = 0;
_this.txt_info.text = "";
// THE FOLLOWING CODE WILL WORK - BUT I NEED IT 20 TIMES :-(
_this.but1.on('click', function () {
schreibe(1);
});
_this.but2.on('click', function () {
schreibe(2);
});
_this.but3.on('click', function () {
schreibe(3);
});
function schreibe(u) {
cnt++;
_this.txt_info.text = "Clicked on button " + u + "\nClick count: " + cnt;
}
What is going wrong? It's me - this is sure 🙂 Please help.
