jQuery append()在动态添加的元素上不起作用 [英] jquery append() not working on dynamically added elements

查看:1535
本文介绍了jQuery append()在动态添加的元素上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑HTML

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

和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

问题是,我需要在dom的所有新添加的元素后附加"x"标记.

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()在动态添加的元素上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆