Append
  • element to
      and add click event fo
  • 2020-06-17 14:28发布

    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.

    10条回答
    兄弟一词,经得起流年.
    2楼-- · 2020-06-17 15:15

    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:

    var li = $('<li />');
    li.click(function() { ... });
    

    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:

    var list = $('#saved-list'); $.each(all_objects, function(i, item) {{
        list.append(
            $('<li />')
                .append(
                    $('<a />').text(item.text)
                )
                .click(function() { ... } );
        );
    });
    
    查看更多
    兄弟一词,经得起流年.
    3楼-- · 2020-06-17 15:18

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

    $("<li />")
      .append(
        $("<a />")
         .attr("href" ,"#saved-route")
         .text(this.text))
      .click(function() {
        // your click event
      })
      .appendTo("#saved-list");
    
    查看更多
    Emotional °昔
    4楼-- · 2020-06-17 15:19
    $.each(all_objects, function() {{
        var list_route = "<li><a href='#saved-route'>" + this.text + "</a></li>";
        var newLi = $(list_route);
        newLi.click( function(){} ).attr("id","foo");
        //if you want the a
        newLi.find("a").click( function(){} ).attr("id","foo");
    
        $('#saved-list').append(newLi);              
    });
    
    查看更多
    ▲ chillily
    5楼-- · 2020-06-17 15:20

    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);
    });
    
    查看更多
    登录 后发表回答