jQuery`Click`,`bind`,`live`,`delegate`,`trigger`和`on`函数之间的区别(有一个例子)? [英] Difference between jQuery `click`, `bind`, `live`, `delegate`, `trigger` and `on` functions (with an example)?

查看:106
本文介绍了jQuery`Click`,`bind`,`live`,`delegate`,`trigger`和`on`函数之间的区别(有一个例子)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读 jQuery官方网站上每个功能的文档,但以下函数之间没有此类比较列表:

I have read the documentation of each function on jQuery official website, but there is no such comparison listings between below functions:

$().click(fn)
$().bind('click',fn)
$().live('click',fn)
$().delegate(selector, 'click', fn)
$().trigger('click') // UPDATED
$().on('click', selector ,fn); // more UPDATED

请避免使用任何参考链接。

Please avoid any reference link.

上述所有功能如何正常工作以及在哪种情况下应该首选?

How do all above functions exactly works and which should be preferred in which situation?

注意:如果还有其他功能(s)具有相同的功能或机制,请详细说明。

Note: If there are any other function(s) having the same functionality or mechanism, Then please elaborate.

我也见过 $。触发器功能。它是否与上述功能类似?

I have also seen a $.trigger function. Does it work similar to the above functions?

现在 .on 添加在 v1.7 和我认为这个在某种程度上涵盖了所有上述功能要求。

Now .on is added in v1.7 and I think this one somehow cover all of above functions requirement together.

推荐答案

在你读这篇文章之前,在另一个页面中提取这个事件列表,API本身非常有用,我在下面讨论的所有内容都是直接从这个链接页面

Before you read this, pull this list of events up in another page, the API itself is tremendously helpful, and all of what I'm discussing below is linked directly from this page.

首先, .click(function) 实际上是的快捷方式 .bind('click',function) ,它们是等效的。将处理程序直接绑定到元素时使用它们,如下所示:

First, .click(function) is literally a shortcut for .bind('click', function), they are equivalent. Use them when binding a handler directly to an element, like this:

$(document).click(function() {
  alert("You clicked somewhere in the page, it bubbled to document");
});

如果此元素被替换或丢弃,此处理程序将不再存在。另外,当运行此代码时,附加处理程序(例如选择器找到它)的元素将不会获得处理程序。

If this element gets replaced or thrown away, this handler won't be there anymore. Also elements that weren't there when this code was run to attach the handler (e.g. the selector found it then) won't get the handler.

.live() .delegate() 同样相关, .delegate() 实际使用 .live() 内部,他们都在听泡沫的事件。 这适用于新旧元素,它们以相同的方式冒泡事件。您可以在元素发生变化时使用这些元素,例如添加新行,列表项等。如果您没有将保留在页面中且不在任何时候替换的父/共同祖先,请使用 .live() ,如下所示:

.live() and .delegate() are similarly related, .delegate() actually uses .live() internally, they both listen for events to bubble. This works for new and old elements, they bubble events the same way. You use these when your elements may change, e.g. adding new rows, list items, etc. If you don't have a parent/common ancestor that will stay in the page and not be replaced at any point, use .live(), like this:

$(".clickAlert").live('click', function() {
  alert("A click happened");
});

但是如果你确实有某个父元素没有被替换(所以它的事件处理程序不是再见,你应该用 .delegate() ,如下所示:

If however you do have a parent element somewhere that isn't getting replaced (so its event handlers aren't going bye bye) you should handle it with .delegate(), like this:

$("#commonParent").delegate('.clickAlert', 'click', function() {
  alert("A click happened, it was captured at #commonParent and this alert ran");
});

这与 .live() ,但事件在被捕获和执行处理程序之前冒泡的次数减少了。这两种方法的另一个常见用法是,您的类更改元素,不再匹配您最初使用的选择器...使用这些方法,选择器在事件发生时进行评估,如果它匹配,处理程序运行...所以元素不再匹配选择器重要,它将不再执行。使用 .click() 但是,事件处理程序绑定在DOM元素上,它与用于查找它的任何选择器都不匹配这一事实是无关紧要的...事件被绑定并且它一直存在直到该元素消失,或者处理程序被移除< a href =http://api.jquery.com/unbind/\"rel =nofollow noreferrer> .unbind()

This works almost the same as .live(), but the event bubbles fewer times before being captured and the handlers executed. Another common use of both of these is say your class changes on an element, no longer matching the selector you originally used...with these methods the selector is evaluated at the time of the event, if it matches, the handler runs...so the element no longer matching the selector matters, it won't execute anymore. With .click() however, the event handler is bound right on the DOM element, the fact that it doesn't match whatever selector was used to find it is irrelevant...the event is bound and it's staying until that element is gone, or the handler is removed via .unbind().

.live的另一个常见用途( ) .delegate() 效果。如果您正在处理 lot 元素,则将单击处理程序直接附加到每个元素是昂贵且耗时的。在这些情况下,设置单个处理程序并让冒泡完成工作更经济,看看这个问题,它产生了巨大的差异,这是应用程序的一个很好的例子。

Yet another common use for .live() and .delegate() is performance. If you're dealing with lots of elements, attaching a click handler directly to each element is expensive and time consuming. In these cases it's more economical to setup a single handler and let bubbling do the work, take a look at this question where it made a huge difference, it's a good example of the application.

触发 - 更新的问题

有两个主要的事件处理程序触发函数,它们属于API中相同的事件处理程序附件类别,这些是 .trigger() .triggerHandler() .trigger('eventName') 一些公共事件内置的快捷方式,例如:

There are 2 main event-handler triggering functions available, they fall under the same "Event Handler Attachment" category in the API, these are .trigger() and .triggerHandler(). .trigger('eventName') has some shortcuts built-in for the common events, for example:

$().click(fn); //binds an event handler to the click event
$().click();   //fires all click event handlers for this element, in order bound

您可以在此查看包含这些快捷方式的商家信息

As为了区别, .trigger() 触发事件处理程序(但不是大多数时间的默认操作,例如将光标放在点击的< textarea> 中的正确位置)。它导致事件处理程序按它们绑定的顺序发生(如本机事件那样),触发本机事件操作,并使DOM冒泡。

As for the difference, .trigger() triggers the event handler (but not the default action most of the time, e.g. placing the cursor at the right spot in a clicked <textarea>). It causes the event handlers to occur in the order they were bound (as the native event would), fires the native event actions, and bubbles up the DOM.

.triggerHandler() 通常用于其他目的,这里你只是试图触发绑定的处理程序,它不会导致本机事件触发,例如提交表格。它不会冒泡DOM,并且它不可链接(它返回该事件返回的最后绑定事件处理程序)。例如,如果您想触发焦点事件但实际上没有聚焦对象,您只需要使用 .focus(fn) 要运行,这样就可以了,而 .trigger() 会做到这一点以及实际关注元素和泡泡了。

.triggerHandler() is usually for a different purpose, here you're just trying to fire the bound handler(s), it doesn't cause the native event to fire, e.g. submitting a form. It doesn't bubble up the DOM, and it's not chainable (it returns whatever the last-bound event handler for that event returns). For example if you wanted to trigger a focus event but not actually focus the object, you just want code you bound with .focus(fn) to run, this would do that, whereas .trigger() would do that as well as actually focus the element and bubble up.

这是一个真实世界的例子:

Here is a real world example:

$("form").submit(); //actually calling `.trigger('submit');`

这将运行任何提交处理程序,例如 jQuery验证插件,然后尝试提交<形式> 。但是,如果只是想要验证,因为它通过提交事件处理程序连接,但不提交<表单> 之后,您可以使用 .triggerHandler('submit ') ,如下所示:

This would run any submit handlers, for example the jQuery validation plugin, then try to submit the <form>. However if you just wanted to validate, since it's hooked up via a submit event handler, but not submit the <form> afterwards, you could use .triggerHandler('submit'), like this:

$("form").triggerHandler('submit');

如果验证检查未通过,该插件会阻止处理程序通过轰炸提交表单,但是用这种方法我们不关心它做什么。无论是否中止,我们都没有尝试提交表单,我们只是想触发它重新验证并且不做任何其他事情。 (免责声明:这是一个多余的例子,因为插件中有一个 .validate()方法,但这是一个很好的说明意图)

The plugin prevents the handler from submitting the form by bombing out if the validation check doesn't pass, but with this method we don't care what it does. Whether it aborted or not we're not trying to submit the form, we just wanted to trigger it to re-validate and do nothing else. (Disclaimer: This is a superfluous example since there's a .validate() method in the plugin, but it's a decent illustration of intent)

这篇关于jQuery`Click`,`bind`,`live`,`delegate`,`trigger`和`on`函数之间的区别(有一个例子)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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