results[i]
is only valid variable at the time machine is inside the for
loop, later on, when event handler is triggered, result[i]
is undefined.
That's why you need to ensure results[i]
gets saved as variable in context of a function.
for(var i=0; i< results.length; i++){
(function(result) {
$('<li>'+result.name+'</li>').appendTo($('ul')).bind('click',function(){
doSomething(result);
})
})(results[i]);
}
Here's working example http://jsfiddle.net/T9aUq/.
Edit: Actually to make it really work, I had to change the way events are registered - at first, click handler was binded to elements matching $('ul') instead of new li element (since append()
function of jQuery doesn't return appended element, but rather sticks to previous scope (which was ul
).