jquery append() not working on dynamically added elements

﹥>﹥吖頭↗ 提交于 2019-12-04 06:15:28

Your code is running right away, and so of course it only has access to the elements that already exist. The code adding new list items is running later, when the user clicks something. You'll have to hook into that process as well.

One way is to hook the same event they are, and run your code from the event handler. Be sure to hook the event after they do.

Their code:

$('button').live('click', function(){
    $('ul').append('<li>Added item</li>');
});

Your code (after theirs):

$('button').live('click', markButtons);

markButtons();

function markButtons() {
    $('ul li:not(.marked)')
        .addClass("marked")
        .append('<b> x</b>');
}

Updated fiddle

The reason I said your code needs to do its hookup after their code is that jQuery guarantees the order of the calls to event handlers: When the event occurs, the handlers are called in the order in which they were attached. By attaching your handler after they attach theirs, you guarantee that your handler is called after theirs has done its thing.

If you're worried about the order getting mixed up, you could always delay your code slightly:

$('button').live('click', function() {
    setTimeout(markButtons, 0);
});

That way, your code is guaranteed to run after all of the event handlers hooked to the click have been run.

You have to repeat the "x" code in the event handler:

$('button').live('click', function(){  //This action is done by an external script.
    $('ul').append(
      $('<li>Added item</li>').append('<b>x</b>')
    ); 
});

Of course you could also just put the bolded "x" right in the <li> when you append it ...

edit If you can't change the click handler, then the only thing you can do is either poll the DOM, or else try something like what @T.J. Crowder suggests (which I think should work just fine).

Why not just do it in the initial append?

$('button').live('click', function(){  //This action is done by an external script.
    $('ul').append('<li>Added item<b> x</b></li>'); 
});

Since it sounds like you don't have access to the script that is doing the append, you could bind your own handler.

$('button').live('click', function(){  //This action is done by an external script.
    setTimeout(function() {
        $('ul li:not(li:has(b))').append('<b> x</b>'); 
    }, 10);
});

This will select li elements that do not currently have a nested b element, and it will append one.

I placed it in a setTimeout since you may not be able to guarantee the order of execution of the handlers.

If you prefer valid CSS selectors, do this instead:

$('ul li').not($('li b').closest('li')).append('<b> x</b>'); 

or this:

$('ul li').not(function() { return $(this).find('b').length; }).append('<b> x</b>'); 

JSFIDDLE DEMO showing the two separate handlers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!