See 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 divs to warn β0β and β1β respectively when I click on them. But both of them warn "2".
When I press the div and the event fires, how and where does the handler find the value of the variable i?
I know that adding closure accomplishes my goal. But why?
javascript scope javascript-events event-handling
Boyang
source share