Variables in click handler
When using variables in click handlers, is there a way to use the value of the variable when the handler was
set instead of
run? For example:
- var links = new Array;
- for (i = 0; i < 5; i++) {
- links[i] = document.createElement('span');
- $("body").append(links[i]);
- $(links[i]).text("Click here!");
- $(links[i]).click(function() {
- alert(i);
- });
- }
All five of the "Click here!" create an alert with the number 5, which was the last value
i was. How can I have each click function use the value of
i when it was looping through (0, 1, 2, 3, 4)? Thanks!