jQuery appended link live() handler not triggering
I have an unordered list of links that I am dynamically adding to on $(document).ready(). I am defining a handler for the live 'click' event on the link I am adding but it's not triggering. I was under the impression using live() over, say click() meant the event handler is attached to elements that are dynamically added to the DOM. Here's a code listing to help illustrate my query.
$(document).ready(function() {
$('.activities ul').each(function() {
appendAddTagLink($(this));
});
});
function appendAddTagLink(ulel) {
var thelink = $('<a>add</a>').attr('href', 'add');
thelink.live('click', function(ev) {
// Not getting here!
})开发者_如何学C;
ulel.append($('<li></li>').append(thelink));
}
I'm extracting the body of the code into a function as I need to reuse it a couple of times. The strange thing is that while the live() handler does not seem to attach to the link, the last line in the function (which appends the link to an
No, in your code you should use bind()
and not live()
.
If you wanted to use live()
, your code should look something like this:
$('.activities ul').each(function() {
$(this).append('<li><a href="add">add</a></li>');
});
// Some selector to grab your 'add' links
$("a[href=add]").live("click", function(){
// Do stuff
});
精彩评论