I need to do something like this:
for(int i =0; i< results.length; i++){
$('ul').append('<li>'+results[i].name+'</li>').bind('click',function(){
doSomething(results[i]);
})
}
but when the click happens, the object passed to doSomething is undefined. How do I solve this?
results[i]is only valid variable at the time machine is inside theforloop, 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.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 wasul).