Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery .click not working as I expected

I have a question about the .click function in Jquery. I have this code:

for (var i = 0; i < 5; i++) {
    var divTest = $('<div></div>');
    divTest.text("My Div " + i);
    divTest.click(function() {
        alert("Alert: Div " + i);
    });
    $('#myTest').append(divTest);
}​

I expected to add five divs to the "myTest" element and for each div the onclick function would show an alert with the corresponding div number.

The divs were added properly, but when I click on the divs I always get the alert with the text: "Alert: Div 5". Why? What I have to change to generate the behavior that I'm expecting?

Here is my jsFiddle: http://jsfiddle.net/BKFGm/2/

like image 758
Rafael Avatar asked Oct 16 '12 22:10

Rafael


2 Answers

In this case you should use closure:

(function(i) {
    divTest.click(function() {
        alert("Div: " + i);
    });
})(i);

DEMO: http://jsfiddle.net/BKFGm/4/


Another option is to pass i in the eventData map:

divTest.click({ i: i }, function(e) {
    alert("Div: " + e.data.i);
});

DEMO: http://jsfiddle.net/BKFGm/11/

like image 170
VisioN Avatar answered Sep 22 '22 14:09

VisioN


Once again, a classic case of closures. i keeps getting incremented, whereas you want to anchor it in the click event. Try this:

for( i=0; i<5; i++) {
  (function(i) {
    // your code that depends on `i` here
  })(i);
}
like image 37
Niet the Dark Absol Avatar answered Sep 22 '22 14:09

Niet the Dark Absol