Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append <li> element to <ul> and add click event for each?

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.

like image 715
phil123 Avatar asked May 24 '11 14:05

phil123


Video Answer


2 Answers

You're better off using .live() or .delegate() than worrying about creating a .click() handler on every element you create. Something like this:

$('#saved-list').delegate('li', 'click', function () {
    // do stuff on click
});

You only have to bind this click listener once, and it will work for every <li> that is a descendant of the element with ID saved-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:

$.each(all_objects, function() {
    var $a = $('<a/>', {
        href: '#saved-route',
        text: this.text
    });

    var $li = $('<li/>', {
        click: function () {
            // do stuff on click
        }
    }).append($a);

    $('#saved-list').append($li);
});
like image 114
Matt Ball Avatar answered Oct 16 '22 12:10

Matt Ball


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...

$.each(all_objects, function() {{
    var list_route = "<li><a href='#saved-route'>" + this.text + "</a></li>";
    $('#saved-list').append(list_route);      
});
$('#saved-list').delegate('li', 'click', function() {
    // do something here each time a descendant li is clicked
});

See delegate

like image 6
lonesomeday Avatar answered Oct 16 '22 12:10

lonesomeday