Possible duplicate:Javascript shameful Loop problem?
For some reason, I get "6" inside my function here for each div element:
for(var i = 1; i <= 5; i++){ $('<div class="e-' + i + '"></div>').appendTo(something).click(function(){ alert(i); // <-- it 6. wtf?? }); }
instead of 1, 2, 3, etc.
The class, on the other hand, seems to be set correctly.
What am I doing wrong?
Your loop forexecutes at page load time. A warning is triggered only when a click event occurs that occurs after the for loop completes. Therefore, the value is inow 6.
for
i
1) Loading a page, the loop fordoes its stuff ...
2) click. i 6, for .
, , i .
:
for(var i = 1; i <= 5; i++) { $('<div class="e-' + i + '"></div>') .appendTo(something) .click(function(value) { return function() { alert(value) }; }(i)); }