问题描述
考虑 HTML
<ul>
<li>Default item</li>
<li>Default item</li>
</ul>
<button>Append</button>
和 jQuery 代码
and the jQuery code
$('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
问题是,我需要将x"标记附加到 dom 中所有新添加的元素.
The thing is, I need to append the "x" mark to all newly added elements to the dom.
在这种情况下,只有默认元素会附加x"标记.
In this case only default elements are appended with the "x" mark.
新添加的元素不附加x".
Newly added elements are not appended by "x".
我相信工作会很简单,但不能把它做好!!
I am sure the work will be simple, but cant get it right !!
现场示例 - http://jsfiddle.net/vaakash/LxJ6f/1/
推荐答案
您的代码会立即运行,因此它当然只能访问已经存在的元素.添加新列表项的代码稍后会在用户单击某些内容时运行.您也必须参与该过程.
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.
他们的代码:
$('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>');
}
更新小提琴
我说你的代码需要在他们的代码之后进行连接的原因是 jQuery 保证了对事件处理程序的调用顺序:当事件发生时,处理程序按顺序调用他们附上了.通过在他们附加他们的处理程序之后附加您的处理程序,您可以保证您的处理程序在他们完成它的事情之后被调用.
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);
});
这样,您的代码可以保证在所有与 click
挂钩的事件处理程序都运行后运行.
That way, your code is guaranteed to run after all of the event handlers hooked to the click
have been run.
这篇关于jquery append() 不适用于动态添加的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!