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('&开发者_运维问答lt;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>');
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.
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);
}
精彩评论