I'd like to add a series of <li>
elements to a <ul>
, and add a click event to each one, programmatically.
I'm not sure how to do this, at least not in a neat, jQueryish way.
This is my existing code:
<ul id="saved-list"></ul>
<script type="text/javascript">
$.each(all_objects, function() {{
var list_route = "<li><a href='#saved-route'>" + this.text + "</a></li>";
$('#saved-list').append(list_route);
// add unique id (this.id) to item and click event here?
// pseudocode - onclick: alert(this.id);
});
$('#saved-list').refresh('listview'); // jquery mobile list refresh
</script>
Please could someone advise how to add a click event to each list item programmatically?
UPDATE: I need to do something slightly different for each list item (let's just say an alert) - apologies for not making this clear.
Isn't it enough to add this in (or after) your current loop?
$('#saved-list li').click(function(){ alert('hello'); });
@Matt Ball is pretty close to the answer here, but I will add a little more clearly that you can do different things with the delegate depending on what element was clicked:
$('#saved-list').refresh('listview'); // jquery mobile list refresh
Note that in the delegate
this
is still referring to theli
that was clicked on.Although I don't know what this
$('#saved-list').refresh('listview')
business is about, the following might be what you're looking for:Note that we avoid appending to the DOM until the last minute, because appending is expensive.
As other posters mention, using a delegated click handler is a better approach, generally. That would look something like
Don't.
Rather than binding a new event handler for each element (which could become quite expensive), bind a single event handler to
#saved-list
, which is a common ancestor. Event bubbling means that ancestor elements are notified of events on their descendants, so you can handle events there instead of on the originating element.Something like this...
See
delegate
You could use the
live
function, the downfall is that you might need some mechanism to determine exactly which of theli
items that have been clicked:This is why
bind
exists.Also, this way is very easy to create different clicks for each item: