我在这里和网上其他地方读过一些关于live()delegate()之间差异的帖子.然而,我还没有找到我想要的答案(如果这是一个骗局,请告诉我).

I know that the difference between live and delegate is that live cannot be used in a chain. I also read somewhere that delegate is in some cases faster (better performance).

My question is, is there a situation where you should use live instead of delegate?

UPDATE

我设置了一个simple test,以查看性能上的差异.

我还添加了jQuery1.7中提供的新.on()+

结果很大程度上总结了答案中所述的性能问题.

  • 除非jQuery版本不支持.delegate(),否则不要使用.live().
  • 除非jQuery版本不支持.on(),否则不要使用.delegate().

.live().delegate()之间的差别比delegate().on()之间的差别要大得多.

推荐答案

I never use live; I consider the benefits of using delegate to be so substantial as to be overwhelming.

The one benefit of live is that its syntax is very close to that of bind:

$('a.myClass').live('click', function() { ... });

但是,delegate使用稍微更详细的语法:

$('#containerElement').delegate('a.myClass', 'click', function() { ... });

然而,在我看来,这似乎更明确地说明了实际发生的事情.从live个例子中,你没有意识到事件实际上是在document上被捕捉到的;对于delegate,事件捕获显然发生在#containerElement.你可以用live做同样的事情,但是语法变得越来越可怕.

Specifying a context for your events to be captured also improves performance. With the live example, every single click on the entire document has to be compared with the selector a.myClass to see if it matches. With delegate, that is only the elements within #containerElement. This will obviously improve performance.

最后,live要求浏览器查找a.myClass whether or not it currently exists.delegate仅在触发事件时查找元素,从而进一步提高了性能优势.


NB delegate在幕后使用live,因此您可以用live做任何可以用delegate做的事情.我的答案是处理它们,因为它们是常用的.

还要注意,在现代jQuery中,livedelegate都不是执行事件委派的最佳方式.新语法(从jQuery 1.7开始)与on函数一起使用.语法如下:

$('#containerElement').on('click', 'a.myClass', function() { ... });

Jquery相关问答推荐

即使我使用 [FromBody] C# 从视图(Ajax)发送请求时在控制器中收到 NULL 对象

javascript 捕获浏览器快捷方式 (ctrl+t/n/w)

用 JS 触发 CSS 悬停

如何从 jQuery 转到 React.js?

在 Javascript 中启用和禁用 Div 及其元素

使用 jQuery,当用户仍在编辑该字段时,如何将文本字段的第一个字母大写?

使用 jQuery 的并行异步 Ajax 请求

jQuery 的 ajax 默认超时值是多少?

JQuery 仅在 Rails 4 应用程序中的页面刷新时加载

jQuery 中 prop() 和 attr() 的区别以及何时使用 attr() 和 prop()

使用 JQuery 获取触发事件的元素的类

为 jQuery AJAX 调用实现加载指示器

如何使用 jQuery 隐藏 div?

如何让 JavaScript/jQuery Intellisense 在 Visual Studio 2008 中工作?

jQuery、复选框和 .is(":checked")

如何在 TypeScript 中获得 jQuery 自动完成功能?

jQuery - 确定输入元素是文本框还是 Select 列表

如何在 Bootstrap 中创建切换按钮

javascript jquery单选按钮单击

jQuery 使用 AND 和 OR 运算符按属性 Select