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.
The
.click
function will bind a click handler function to any given element. As the comments in your code mention you can use the ID or other means to select the item after it's been DOM-ized but another way to do this is simply to reference the variable that contains the element you want to bind.Example:
This is probably somewhat stylistic, but one of the features of jQuery is that it is chainable. This means that jQuery function calls always return a reference to the wrapped set of jQuery itself. Using the chainable aspect, you could re-write the above code like so:
hello phil in jquery you can create dom object without adding them as text to the dom. this will give you a chans to manipulate them before they are added (and after to).
You're better off using
.live()
or.delegate()
than worrying about creating a.click()
handler on every element you create. Something like this:You only have to bind this click listener once, and it will work for every
<li>
that is a descendant of the element with IDsaved-list
.If you do want to create a separate click handler for every
<li>
(I don't recommend this though) here's a nice way to do it: