开发者

jQuery appended link live() handler not triggering

开发者 https://www.devze.com 2023-02-20 11:45 出处:网络
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 u

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

  • element and then to the element works just fine. Also I am getting no javascript syntax errors.


    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
    });
    
  • 0

    精彩评论

    暂无评论...
    验证码 换一张
    取 消