Strange value for counter variable in javascript

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?

+3
source share
2 answers

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.

1) Loading a page, the loop fordoes its stuff ...

2) click. i 6, for .

+11

, , i .

:

for(var i = 1; i <= 5; i++)
{
  $('<div class="e-' + i + '"></div>')
    .appendTo(something)
    .click(function(value)
    { 
      return function() { alert(value) };
    }(i));
}
+5

All Articles