1.7.2中的jQuery事件委托 [英] jQuery event delegation in 1.7.2

查看:84
本文介绍了1.7.2中的jQuery事件委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了从$(document)进行委派以外,是否有任何方法可以使用jQuery委派一个事件,该事件将与匹配选择器的页面上的所有元素相对应?

Is there any way to delegate an event using jQuery that will correspond to all elements on the page that match the selector, other than delegating from $(document)?

由于这可能是措辞不佳的,因此有一个麻烦之处:

Since that's probably poorly worded, here's the rub:

曾经有jQuery.live将事件委派给所有与选择器匹配的元素.这由jQuery.delegate取代,后者将特定上下文选择器中的事件委派给其子级,而子元素又由jQuery.on取代,该子实际上执行相同的操作,但是背后有不同的位(我想像).

There used to be jQuery.live that delegated events to all elements that matched the selector. This was superseded by jQuery.delegate which delegated events within a specific context selector to its children, which in turn was superseded by jQuery.on, which does effectively the same thing, but with different bits behind the scenes (I'd imagine).

我想做的是,将安全的事件处理程序添加到页面上的每个div.foo上,无论它可能存在于何处或何时存在.根据文档和经验研究,以下内容将仅绑定到脚本运行时存在的.foo元素.由于有些代码可能会在以后的页面上放置.foo元素,因此无法完全正常工作.

What I want to do, is safely add an event handler to every div.foo on my page, regardless of where it might live, or when it might live. According to the documentation, and empirical research, the following will only bind to .foo elements that exist when the script is run. Since there is code that might place a .foo element on the page later, this doesn't exactly work.

jQuery('.foo').on('click', handler);

由于不推荐使用live(可能已删除?),所以我尝试不使用它,但是我能想到的唯一解决方案是

Since live is deprecated (possibly removed?), I'm trying to not use that, but the only solution I can come up with is

jQuery(document).on('click', '.foo', handler);

但这不是live最初在幕后所做的吗?更重要的是,有什么重要的理由去做吗?

But isn't this what live did originally, behind the scenes? More to the point, are there any significant reasons not to do this?

我们专门使用的是1.7.2版,但是通用的jQuery答案也有帮助.

We're specifically using version 1.7.2, but generic jQuery answers would help too.

推荐答案

事件从事件的源头一直冒到委托的对象,因此您应该在最低级别的公共父级上使用jquery().on.如果那是文档,那就这样吧.

The events bubble from their source, to whatever they're delegated, so you should use jquery().on at what ever level is the lowest common parent. If that's document, then so be it.

否则,如果您的.foo项目总是在.foocontainer(或其他内容)中创建的,那么即使其中有多个,您也可以在选择器中使用它-您最终会附加.

Otherwise, if your .foo items are always created within a .foocontainer (or something) then you can use that in your selector, even if there is more than one of them - you just end up attaching.

我认为委派回文档的问题在于,它可能要求事件冒泡很多次,从而在过程中产生额外的开销,因此最好将事件委派到尽可能靠近源的地方.

I think the issue with delegating back to document is that it potentially requires the event to bubble a large number of times, incurring extra overhead in the process, so best to delegate the event as close to the source as possible.

这篇关于1.7.2中的jQuery事件委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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