Javascript jquery append()不适用于动态添加的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8376414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:44:33  来源:igfitidea点击:

jquery append() not working on dynamically added elements

javascriptjqueryclickappend

提问by Aakash Chakravarthy

Consider the HTML

考虑 HTML

<ul>
    <li>Default item</li>
    <li>Default item</li>
</ul>
<button>Append</button>

and the jQuery code

和 jQuery 代码

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

$('ul li').append('<b> x</b>'); // This action is done by me

The thing is, I need to append the "x" mark to all newly added elements to the dom.

问题是,我需要将“x”标记附加到 dom 的所有新添加元素。

In this case only default elements are appended with the "x" mark.

在这种情况下,只有默认元素会附加“x”标记。

Newly added elements are not appended by "x".

新添加的元素不附加“x”。

I am sure the work will be simple, but cant get it right !!

我相信工作会很简单,但不能把它做好!!

Live example - http://jsfiddle.net/vaakash/LxJ6f/1/

现场示例 - http://jsfiddle.net/vaakash/LxJ6f/1/

回答by T.J. Crowder

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 afterthey do.

一种方法是挂钩相同的事件,并从事件处理程序运行您的代码。一定要他们做完之后钩住事件。

Their code:

他们的代码:

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

Your code (aftertheirs):

您的代码(他们之后):

$('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 aftertheir 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.

我说你的代码需要它们的代码之后进行连接的原因是 jQuery 保证对事件处理程序的调用顺序:当事件发生时,处理程序按照它们被附加的顺序调用。通过在他们附加他们的处理程序之后附加您的处理程序,您可以保证在他们的处理程序完成其操作后调用您的处理程序。

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 clickhave been run.

这样,您的代码可以保证在所有挂钩到 的事件处理程序都运行后click运行。

回答by Pointy

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

您必须在事件处理程序中重复“x”代码:

$('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 ...

当然,您也可以在<li>附加它时将加粗的“x”放在正确的位置...

editIf 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).

编辑如果您无法更改点击处理程序,那么您唯一可以做的就是轮询 DOM,或者尝试类似 @TJ Crowder 建议的内容(我认为应该可以正常工作)。

回答by RightSaidFred

Why not just do it in the initial append?

为什么不直接在初始 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 lielements that do not currently have a nested belement, and it will append one.

这将选择li当前没有嵌套b元素的元素,并附加一个。

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

我将它放在 a 中,setTimeout因为您可能无法保证处理程序的执行顺序。

If you prefer valid CSS selectors, do this instead:

如果您更喜欢有效的 CSS 选择器,请改为执行以下操作:

$('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 DEMOshowing the two separate handlers.

JSFIDDLE 演示显示了两个单独的处理程序。