Variable scoping and event handler
dom-events, event-handling, javascript, scope
Solution
function MyFunc() {
for (var i = 0; i < 2; i++) { // i= 0, 1
(function(j) {
var myDiv = $('<div>');
myDiv.click(function(e) {
alert(j);
});
$('body').append(myDiv);
})(i);
}
}
var myFunc = new MyFunc();
The code above is how you get it work correctly. Without an closure, you always the the last value of i. What we do is to post i into the closure and let the runtime "remember" the value of that very moment.
Problem
Please see the jsfiddle: http://jsfiddle.net/LsNCa/2/ ``` function MyFunc() { for (var i = 0; i < 2; i++) { // i= 0, 1 var myDiv = $('<div>'); myDiv.click(function(e) { alert(i); // both the two divs alert "2", not 0 and 1 as I expected }); $('body').append(myDiv); } } var myFunc = new MyFunc(); ``` I want the divs to alert "0" and "1" respectively when I click them, but both of them alert "2". When I click the divs and the event is triggered, how and where do the handler find the value of the variable `i`? I'm aware that adding a closure achieves my goal. But why?