0

I have function that creates a button at runtime. I pass the caption and on the onClick function to it like this:

button1 = new buttonControl("caption1", function(){buttonClick(1);});

That works fine but let's say I have 20 of these:

button1 = new buttonControl("caption1", function(){buttonClick(1);});
button2 = new buttonControl("caption2", function(){buttonClick(2);});
button3 = new buttonControl("caption3", function(){buttonClick(3);});
...
button20 = new buttonControl("caption20", function(){buttonClick(20);});

How can I create these in a for loop? If I try this:

button = [];
for (i = 1; i < 21) i++) button[i] = new buttonControl("caption" + i, function(){buttonClick(i);});

This does not work because each button will just call buttonClick(21) because that is the last value of i. My buttonClick function needs to know which button called it based on the passed parameter.

kbriggs
  • 1,267
  • 1
  • 12
  • 16

0 Answers0