事件处理程序无法处理动态内容 [英] Event handler not working on dynamic content

查看:95
本文介绍了事件处理程序无法处理动态内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标签A,在单击该标签时,它会附加另一个标签B以在单击时执行操作B.因此,当我单击标签B时,将执行操作B.但是,.on方法似乎不适用于动态创建的标记B.

I have a tag A in which when clicked on, it appends another tag B to perform an action B on click. So when I click on tag B, action B is performed. However, the .on method does not seems to be working on the dynamically created tag B.

我的标签A的html和jquery如下:

My html and jquery for tag A is as below:

<a id="address" class="add_address btn btn-inverse btn-medium pull-right push-top">Add Shipping address</a>

$('.add_address').click(function(){
    //Add another <a>
    $(document).append('<a id="address"  class="pull-right update btn btn-inverse btn-medium push-top">Update</a>');
})

单击标签B时,将执行某些操作B.我的jQuery如下:

When tag B is clicked, some action B is performed. My jquery is as below:

$('.update').on('click',function(){
  //action B
});

我有一些非动态内容,其类也为".update".在上述.on()方法中,非动态内容适用,但动态内容无效.

I have some non dynamic content which has class ".update" as well. In the .on() method above works fine for the non dynamic content, but not for the dynamic content.

如何使它适用于动态内容?

How can I make it work for dynamic content?

推荐答案

必须添加选择器参数,否则事件将直接绑定而不是委托,仅当元素已经存在时才起作用(因此不起作用)用于动态加载的内容.

You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content).

请参见 http://api.jquery.com/on/#direct-and-delegated-事件

将代码更改为

$(document.body).on('click', '.update' ,function(){

jQuery集合接收事件,然后将其委托给与作为参数指定的选择器匹配的元素.这意味着与使用live时相反,执行代码时jQuery set元素必须存在.

The jQuery set receives the event then delegates it to elements matching the selector given as argument. This means that contrary to when using live, the jQuery set elements must exist when you execute the code.

由于这个答案引起了广泛关注,因此有两个补充建议:

As this answers receives a lot of attention, here are two supplementary advises :

1)(如果可能),请尝试将事件侦听器绑定到最精确的元素,以避免无用的事件处理.

1) When it's possible, try to bind the event listener to the most precise element, to avoid useless event handling.

也就是说,如果要将类b的元素添加到ID为a的现有元素中,请不要使用

That is, if you're adding an element of class b to an existing element of id a, then don't use

$(document.body).on('click', '#a .b', function(){

但是使用

$('#a').on('click', '.b', function(){

2)请注意,添加带有ID的元素时,请确保不要将其添加两次.在HTML中具有两个具有相同id的元素不仅是非法的",而且还会破坏很多东西.例如,选择器"#c"将仅检索具有此ID的一个元素.

2) Be careful, when you add an element with an id, to ensure you're not adding it twice. Not only is it "illegal" in HTML to have two elements with the same id but it breaks a lot of things. For example a selector "#c" would retrieve only one element with this id.

这篇关于事件处理程序无法处理动态内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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