简体   繁体   中英

How can I attach event handlers to dynamically-generated DOM elements using jQuery?

I have a <ul> tag that I want to append some <li> tags inside. Example:

$('body').append("<ul id='myUL'>").find("ul");
$('#myUL').append('<li id='a'>a</li>');
$('#myUL').append('<li id='b'>b</li>');

I want to give every <li> a different click event. How can I accomplish that?

Try something like this:

$('<ul></ul>')
    .attr('id', 'myUL')
    .append(
        $('<li>a</li>').click(function() {
            alert('First one clicked');
        })
    )
    .append(
        $('<li>b</li>').click(function() {
            alert('Second one clicked');
        })
    )
    .appendTo('body')
;
var firstLi = $('<li id='a'>a</li>');
firstLi.click(function() { ... });
$('body').append("<ul id='myUL'>").find("ul");
$('#myUL').append(firstLi);
$('#myUL').append('<li id='b'>b</li>');

try this

$('body').append("<ul id='myUL'>").find("ul");
$('#myUL').append('<li id='a' onclick="myeventHandler(event)" >a</li>');
$('#myUL').append('<li id='b' onclick="myeventHandler(event)" >b</li>');

function myeventHandler(ev){
        var target = ev.target || ev.srcElement;
          alert(target.id);
}

Can't you just put some marker on the list item and give them all the same event? Or, better yet, use a live() event and then you don't even need to add one:

$('#myUL').append('<li id='a'>a</li>');

with:

$(function() {
  $("#myUL li").live("click", function() {
    if (this.id == "a") {
      ...
    }
  });
});

Otherwise just reverse the order and the syntax is much nicer:

$"<li></li>").attr("id", "a").text("a").appendTo("#myUL").click(function() {
  ...
});

You could simply do this:

$"<li id='" + a + "'>" + a + "</li>")..appendTo("#myUL").click(function() {
  ...
});

but I don't recommend this when dealing with dynamic input because you may not properly escape special characters whereas calling attr() and text() will correctly escape content and make you less susceptible to XSS exploits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM