jQuery:live()vs delegate() [英] jQuery: live() vs delegate()

查看:144
本文介绍了jQuery:live()vs delegate()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的网络应用程序中使用jQuery。在阅读其文档时,我读到了 live() delegate()。虽然他们已经解释了这两种方法,但我不明白它们之间的确切区别。还不确定哪种方法在哪种情况下是理想的。

I'm using jQuery in my web application. While reading its documentation I read about live() and delegate(). Although they have explained both methods, I don't understand the exact difference between them. Also not sure about which method is ideal in which scenario.

请帮助我清楚地了解这些方法。

Please help me to get clear understanding of these methods.

谢谢

推荐答案

.live() 要求你立即运行选择器,除非你使用的结果非常浪费。此处的事件处理程序附加到文档,因此必须检查来自任何元素冒泡的该类型的所有事件。这是一个用法示例:

.live() requires you run the selector immediately, unless you're using the result it's very wasteful. The event handler here is attached to document, so all event of that type from any elements bubbling must be checked. Here's a usage example:

$(".myClass").live("click", function() { alert("Hi"); });

注意语句 $(。myClass)运行该选择器以查找具有该类的所有元素,即使我们不关心它们,我们想要的所有都是字符串 .myClass以及以后的 点击事件冒泡到文件

Note that the statement $(".myClass") ran that selector to find all elements with that class even though we don't care about them, all we wanted was the string ".myClass" to match later when click events bubble up to document.

.delegate() 实际使用 .live() 内部,但带有上下文。选择器立即运行,因此它已经更高效,并且它没有附加到文档(虽然可以)它更加本地化...并且当你冒泡时,从来没有检查过来自你不关心的其他元素树的所有其他事件...再次更高效。这是一个用法示例:

.delegate() actually uses .live() internally, but with a context. The selector is not run immediately, so it's more efficient already, and it doesn't attach to document (though it can) it's much more local...and all those other events from other element trees you don't care about are never even checked when bubbled...again more efficient. Here's a usage example:

$("#myTable").delegate("td", "click", function() { alert("Hi"); });

现在发生了什么?我们运行 $(#myTable)来获取要附加的元素(确实比文档更贵,但是我们使用结果。然后我们将一个事件处理程序附加到那个(或其他情况下)元素。只有点击来自 中的元素会在td选择器发生时检查,而不是无处不在 c>。 live()确实(因为所有都在文档里面)。

Now what happened here? We ran $("#myTable") to get the element to attach to (admittedly more expensive than document, but we're using the result. Then we attach an event handler to that (or those in other cases) elements. Only clicks from within that element are checked against the "td" selector when they happen, not from everywhere like .live() does (since everything is inside document).

这篇关于jQuery:live()vs delegate()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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