Javascript jQuery `click`、`bind`、`live`、`delegate`、`trigger` 和 `on` 函数之间的区别(举个例子)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2954932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:39:52  来源:igfitidea点击:

Difference between jQuery `click`, `bind`, `live`, `delegate`, `trigger` and `on` functions (with an example)?

javascriptjquery

提问by diEcho

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

我已经阅读了每个函数的文档 jQuery official website,但在以下函数之间没有这样的比较列表:

$().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?

以上所有功能是如何工作的,在哪种情况下应该优先使用?

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

注:如果有其他功能或机制相同的功能,请详细说明。

Update

更新

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

我也看到了一个$.trigger函数。它的工作方式与上述功能类似吗?

More Update

更多更新

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

现在.on是在v1.7中添加的,我认为这个以某种方式涵盖了上述所有功能要求。

回答by Nick Craver

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.

在您阅读本文之前,将这个事件列表拉到另一个页面中,API 本身非常有用,我在下面讨论的所有内容都直接从此页面链接

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:

首先,.click(function)字面上是 的快捷方式.bind('click', function),它们是等价的。在将处理程序直接绑定到 element时使用它们,如下所示:

$(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 runto attach the handler (e.g. the selector found it then) won't get the handler.

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

.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:

.live()并且.delegate()是类似的相关,.delegate()实际上在.live()内部使用,它们都侦听冒泡的事件。 这适用于新元素和旧元素,它们以相同的方式冒泡事件。当您的元素可能更改时使用这些,例如添加新行、列表项等。如果您没有将留在页面中且不会在任何时候被替换的父/公共祖先,请使用.live(),如下所示:

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

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:

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

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

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(),但事件在被捕获和处理程序执行之前冒泡的次数更少。这两者的另一个常见用途是说你的类在一个元素上发生了变化,不再匹配你最初使用的选择器……使用这些方法,选择器在事件发生时被评估,如果匹配,处理程序运行.. .so 元素不再匹配选择器很重要,它将不再执行。随着.click()然而,事件处理程序的DOM元素上绑定的权利,但事实上,它不匹配任何选择来发现这是无关紧要的......该事件被约束,它一直待到该元素消失了,或者处理器通过 删除.unbind()

Yet another common use for .live()and .delegate()is performance. If you're dealing with lotsof elements, attaching a click handler directly to each element is expensive and time consuming. In these cases it's more economical to setup a singlehandler 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.

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



Triggering- for the updated question

触发- 针对更新的问题

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:

有 2 个主要的事件处理程序触发函数可用,它们属于 API 中相同的“事件处理程序附件”类别,它们是.trigger().triggerHandler().trigger('eventName')为常见事件内置了一些快捷方式,例如:

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

You can view a listing including these shortcuts here.

您可以在此处查看包含这些快捷方式的列表

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.

至于区别,.trigger()触发事件处理程序(但不是大多数时间的默认操作,例如将光标放在 clicked 中的正确位置<textarea>)。它使事件处理程序按照它们被绑定的顺序发生(就像本地事件一样),触发本地事件操作,并冒泡 DOM。

.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 focusevent 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.

.triggerHandler()通常用于不同的目的,在这里您只是尝试触发绑定处理程序,它不会导致本地事件触发,例如提交表单。它不会冒泡 DOM,并且它不可链接(它返回该事件的最后绑定事件处理程序返回的任何内容)。例如,如果您想触发一个focus事件但实际上并不聚焦对象,您只想.focus(fn)运行绑定的代码,这会做到这一点,而.trigger()会做到这一点以及实际聚焦元素并冒泡。

Here is a real world example:

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

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

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

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

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

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 tryingto 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)

如果验证检查未通过,插件会通过轰炸来防止处理程序提交表单,但是使用这种方法我们不关心它做了什么。无论是中止与否我们不试图提交表单,我们只是想把它触发重新验证和别的什么也不做。(免责声明:这是一个多余的例子,因为.validate()插件中有一个方法,但它很好地说明了意图)

回答by Fyodor Soikin

The first two are equivalent.

前两个是等价的。

// The following two statements do the same thing:
$("blah").click( function() { alert( "Click!" ); } );
$("blah").bind( "click", function() { alert( "Click!" ); } ); 

The second one, though, can be used to bind to more than one event at the same time, by specifying several space-separated event names:

但是,通过指定几个以空格分隔的事件名称,第二个事件可用于同时绑定到多个事件:

$("blah").bind( "click mouseover mouseout", function() { alert( "Click! Or maybe mouse moved." ); } ); 

The .livemethod is more interesting. Consider the following example:

.live方法是更有趣。考虑以下示例:

<a class="myLink">A link!</a>
<a id="another">Another link!</a>

<script>
    $("a.myLink").click( function() { alert( 'Click!' ); } );

    $("a#another").addClass( "myLink" );
</script>

After the second line of the script executes, the second link will also have a CSS class of "myLink". But it will not have the event handler, because it didn't have the class when the event was attached.

在脚本的第二行执行后,第二个链接也将有一个“myLink”的 CSS 类。但它不会有事件处理程序,因为在附加事件时它没有类。

Now consider you wanted it to be the other way around: every time a link with class "myLink" appears somewhere on the page, you want it to have the same event handler automatically. This is very common when you have some kind of lists or tables, where you add rows or cells dynamically, but want them all to behave in the same way. Instead of going to all the pain of assigning event handlers anew every time, you can use the .livemethod:

现在考虑一下您希望它是另一种方式:每次在页面上的某个位置出现带有“myLink”类的链接时,您都希望它自动具有相同的事件处理程序。当您有某种列表或表格时,这很常见,您可以在其中动态添加行或单元格,但希望它们都以相同的方式运行。您可以使用以下.live方法,而不是每次都重新分配事件处理程序的所有痛苦:

<a class="myLink">A link!</a>
<a id="another">Another link!</a>

<script>
    $("a.myLink").live( "click", function() { alert( 'Click!' ); } );

    $("a#another").addClass( "myLink" );
</script>

In this example, the second link will also get the event handler as soon as it gets the "myLink" class. Magic! :-)

在本例中,第二个链接也将在获得“myLink”类后立即获得事件处理程序。魔法!:-)

Of course, it's not that literal. What .livereally does is attach the handler not to the specified element itself, but to the very root of the HTML tree (the "body" element). Events in DHTML have this funny feature of "bubbling up". Consider this:

当然,这不是字面意思。什么.live确实是处理程序不附加到指定元素本身,而是对HTML树(“身体”元素)的根源。DHTML 中的事件具有“冒泡”这个有趣的特性。考虑一下:

<div> <a> <b>text</b> </a> </div>

If you click on "text", then first the <b> element will get a "click" event. After that, the <a> element will get a "click" event. And after that the <div> element will get a "click" event. And so on - all the way up to the <body> element. And that's where jQuery will catch the event and see if there are any "live" handlers which apply to the element that caused the event in the first place. Neat!

如果您单击“文本”,那么首先 <b> 元素将获得“单击”事件。之后, <a> 元素将获得一个“点击”事件。之后 <div> 元素将获得一个“点击”事件。依此类推 - 一直到 <body> 元素。这就是 jQuery 将捕获事件并查看是否有任何“实时”处理程序适用于首先导致事件的元素的地方。整洁的!

And finally, the .delegatemethod. It simply takes all the children of your element that conform to the given selector and attach a "live" handler to them. Take a look:

最后,.delegate方法。它只是获取符合给定选择器的元素的所有子元素,并为它们附加一个“实时”处理程序。看一看:

$("table").delegate( "td", "click", function() { alert( "Click!" ); } );

// Is equivalent to:
$("table").each( function() {
    $(this).find( "td" ).live( "click", function() { alert( "Click!" ); } );
} );

Questions?

问题?

回答by Jonathan Tonge

As of jQuery 1.7, the .live() method was deprecated. If you are using a jQuery version < 1.7 than it is officially recommended to use .delegate() over .live().

从 jQuery 1.7 开始,不推荐使用 .live() 方法。如果您使用的 jQuery 版本 <1.7,那么官方建议使用 .delegate() 而不是 .live()。

.live() has now been replace with .on().

.live() 现在已替换为 .on()。

Best to go directly to the jQuery site for more information, but here are the current versions of the .on() method:

最好直接访问 jQuery 站点以获取更多信息,但这里是 .on() 方法的当前版本:

.on( events [, selector] [, data], handler(eventObject) )
.on( events-map [, selector] [, data] )

http://api.jquery.com/on/

http://api.jquery.com/on/

回答by fbuchinger

$().click(fn)and $().bind('click', fn)are identical at first sight, but the $.bindversion is more powerful for two reasons:

$().click(fn)$().bind('click', fn)乍一看完全相同,但由于$.bind两个原因,该版本更强大:

  1. $().bind()allows you to assign one handler to multiple events, for example, $().bind('click keyup', fn).
  2. $().bind()supports namespaced events - a powerful feature if you want to remove (unbind) only certain event handlers that an element is bound to - read more in Namespaced Events.
  1. $().bind()允许您将一个处理程序分配给多个事件,例如,$().bind('click keyup', fn)
  2. $().bind()支持命名空间事件 - 如果您只想删除(解除绑定)元素绑定的某些事件处理程序,这是一项强大的功能 - 在Namespaced Events 中了解更多信息。

Live vs delegate: this has already been answered in the other replies.

直播 vs 委托:这已经在其他回复中回答了。

回答by Dan Beam

This is where reading the API might help. However, I know off the top of my head, so you can continue being lazy (yay!).

这就是阅读 API 可能有所帮助的地方。但是,我很清楚,所以你可以继续偷懒(是的!)。

$('#something').click(fn);
$('#something').bind('click',fn);

There's no difference here (that I know of). .clickis simply a convenience/helper method to .bind('click'

这里没有区别(我知道)。 .click只是一种方便/辅助方法.bind('click'

// even after this is called, all <a>s in
// <div class="dynamic_els"> will continue
// to be assigned these event handlers

$('div.dynamic_els a').live(‘click',fn);

This is very different, as .liveadds events to the selector you pass in (which you haven't here) and continues to look at the DOM as nodes are inserted / removed

这是非常不同的,因为.live将事件添加到您传入的选择器(您没有在这里)并在插入/删除节点时继续查看 DOM

$('#some_element').delegate('td','click',fn);

This is only different because of the way you're assigning event handlers. .delegateis centered on DOM event bubbling. The basic principle is that every event bubbles upward through the DOM tree until it reaches the root element (documentor windowor <html>or <body>, I can't remember exactly).

这只是因为您分配事件处理程序的方式不同。 .delegate以DOM事件冒泡为中心。基本原则是每个事件都向上冒泡通过 DOM 树,直到它到达根元素(documentorwindow<html>or <body>,我记不清了)。

Either way, you're binding an onclickhandler to a all the <td>s within $('#some_element')(you must specify a selector, though you could say $(document)). When one of its children is clicked, the event bubbles up to the <td>. You can then extract the source element of the event (which jQuery does for you automagically).

无论哪种方式,您都将一个onclick处理程序绑定到其中的所有<td>s $('#some_element')(您必须指定一个选择器,尽管您可以说$(document))。当单击它的一个子项时,事件冒泡到<td>. 然后,您可以提取事件的源元素(jQuery 会自动为您完成)。

This is useful when there are tons of elements and you only have only a few (or one central) point[s] that these events will go through. This saves the browser effort and memory to consolidate these event handlers into less objects.

当有大量元素并且您只有几个(或一个中心)点可以通过这些事件时,这很有用。这节省了浏览器将这些事件处理程序合并到更少的对象中的工作量和内存。