Possible Duplicate:
Javascript infamous Loop problem?
For some reason I get “6” inside my function here for every div element:
for(var i = 1; i <= 5; i++){
$('<div class="e-' + i + '"></div>').appendTo(something).click(function(){
alert(i); // <-- it's 6. wtf??
});
}
instead of 1, 2, 3, etc.
The class on the other hand it appears to be correctly set..
What am I doing wrong?
Your
forloop is being executed at page load time. The alert only fires when there’s a click event which is happening after the for loop has finished. Hence the value ofiis now 6.1) Page loads,
forloop does its stuff…2) Sometime later a click event is fired. the value of
iat this time is 6 because theforloop has already completed.