See http://jsfiddle.net/tAfkU/
When I’m looping through an array, how can I refer to the correct element of the array when I’ve bound callbacks in the loop?
var items = ["a", "b", "c"];
for(var i in items) {
var this_item = items[i];
var new_li = $('<li>'+this_item+'</li>');
new_li.bind('click', function() {
alert(this_item); // this always alerts "c"
});
$('.container').append(new_li);
}
You’ll want to create a closure over that variable:
Remember that the bound function is called later then that loop finishes so the value of this_item is whatever it was set to lastly. Javascript doesn’t create a new scope for every loop iteration so if you want to define callbacks you have to create one yourself. The only way you can create scopes in JS is via functions. So I wrote a function that binds the value as an argument and returns a new function that will now “remember” the proper value.