I’m trying to create a bunch of buttons via loop, and use the loop iterator as an argument for each of the button onclick functions.
My code:
var testFnc = function(i) { alert("Arg: " + i); }
mainDiv.append(create_button(name, "buttonCSS", testFnc(i)));
However the functions are called automatically as the page loads and the buttons are placed (i.e. I see the alerts right away).
I’m sure there’s some common design pattern for this.
Thanks!
One approach is to, for each button, call a “self-executing” function that creates a separate function.
This will allow you to change the value of
ioutside the function and leave existing buttons unaffected.(If you are creating a lot of buttons (perhaps thousands), it might be better to change the
create_buttonfunction to add a property to the button element itself and have your function check that. Or if your code does not need to work in Internet Explorer 8 or below, you can use thebind()function instead of the above code.)