I am currently populating a list dynamically based on some web calls. When these calls return I use an HTML template to add another item to the list based on the call response. I also am trying to attach some events to these objects using jQuery, but when I generate the items it seems like only the last item generated has the appropriate events firing.
So here is the code:
The javascript generates the html string and the adds it to the list:
List.innerHTML += html;
The html is generated using moustache.js and renders properly, I set the id in the template before adding it.
The template has this form:
var template = '<li style="width:400px; height:100px" id="{{id}}" ><img src="{{source}}" style="float:left"/>{{title}} <button id="{{id}}button">Delete</button></li>';
Where all the elements are replaced appropriately.
Then I try to attach a click event to the button and a double click event to the entire list object:
$('#' +id +'button').bind('click', function() {
//SOME STUFF GOES HERE
});
$('#' +id +'button').bind('dblclick', function() {
//MORE STUFF GOES HERE
});
Im not sure why the event wouldnt attach to each object, am I missing something?
Thanks!
The DOM might not have been updated on the browser by the time you add the click handlers. You have a couple options:
Example 1:
Example 2: