Reputation: 811
I need to set events to elements makes "on the fly", like var X = $('HTML CODE HERE')
, but when I set the events to the last element, all other elements get this last event.
Example here: http://jsfiddle.net/QmxX4/6/
$(document).ready(function() {
var ulItem = $('.lst');
for (var x=0; x<5; x++) {
var newItemElement = $('<li style="border:solid 1px blue;width:200px;height:40px;"></li>');
ulItem.append(newItemElement);
var generator = Math.random();
newItemElement.on('click', function() {
console.log(generator);
});
}
});
All elements are diferents, and I attach the event in the element directly, im try to append before and after add event to element, but not work, all element get the last event.
If you make click in the <li></li>
get code generated in the last event, but "in theory" all elements have diferent events attached..
But if I make other loop appending elements after append al items to <ul></ul>
, like this:
$.each($(ulItem).children('li'), function(i, item) {
console.log($(this));
var generator = Math.random();
$(this).on('click', function() {
console.log(generator);
});
});
Works... what is the problem?
Upvotes: 0
Views: 83
Reputation: 55392
In your first loop, the generator
variable belongs to the ready
callback function, and the inner log functions all share it.
In your second loop, the generator
variable belongs to the each
callback function which is called once for each item and therefore the log functions all see a different variable.
Upvotes: 2