0

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?

Ry-
  • 218,210
  • 55
  • 464
  • 476
Zenth
  • 769
  • 2
  • 7
  • 23
  • possible duplicate of [Doesn't JavaScript support closures with local variables?](http://stackoverflow.com/questions/643542/doesnt-javascript-support-closures-with-local-variables) – Neil Aug 22 '12 at 23:38
  • Thanks, little example of my problem here, i go to anonymous function to solve this problem. thanks! – Zenth Aug 23 '12 at 09:59

1 Answers1

2

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.

Neil
  • 54,642
  • 8
  • 60
  • 72