Javascript jQuery .click() callback references local variable from the calling method instead of cop

Posted by Eric Freese on Stack Overflow See other posts from Stack Overflow or by Eric Freese
Published on 2010-05-07T19:54:31Z Indexed on 2010/05/07 19:58 UTC
Read the original article Hit count: 97

The following jQuery Javascript code is included on an otherwise empty page.

$(function() {
  for (var i = 0; i < 10; i++) {
    element = $('<div>' + i + '</div>');
    element.click(function() {
      alert(i);
    });
    $('body').append(element);
  }
});

The desired behavior is that this code should generate 10 div elements numbered from 0 to 9. When you click on a div element, an alert popup will show the number of the div element you clicked on (i.e. if a user clicks on the div element labeled '4', the alert popup should show the number 4).

The alert popup instead shows the number 10 regardless of which div element is clicked on.

How can I modify this code to make it behave in the desired way?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery