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/