Home > Article > Web Front-end > Sharing examples of the differences between .bind(), .live(), .delegate() and .on() in Jquery
This article mainly shares with you the differences between .bind(), .live(), .delegate() and .on() in Jquery. .bind() and .live are often used in our daily development. (), .delegate() and .on(), some students have some doubts about these four, so the following article mainly introduces to you about .bind(), .live(), .delegate() in Jquery ) and .on(), I hope it can help everyone.
Introduction
I recently learned that many web developers have a lot of doubts about the .bind() .live() .delegate() and .on() methods in jquery. These questions usually revolve around what the real differences are between them and when to use them. The following article will give you a detailed introduction to the differences between these four methods. Each method is introduced in detail. Without further ado, let’s take a look at the detailed introduction:
Let’s go deeper Before understanding these methods, let's first take a common piece of HTML as a sample for us to write jquery sample methods.
<ul id="members" data-role="listview" data-filter="true"> <!-- ... 其他li ... --> <li> <a href="detail.html?id=10" rel="external nofollow" > <h3>John Resig</h3> <p><strong>jQuery Core Lead</strong></p> <p>Boston, United States</p> </a> </li> <!-- ... 其他li ... --> </ul>
Use the Bind method
.bind() method to register the event type and an event handling function directly into the selected DOM element. This method has been used for the longest time, and during this period, it solved various cross-browser problems very well. When using it to connect event handlers, it is still very concise, but there are also some performance issues, which will be listed below.
/* .bind() 方法将事件类型和一个事件处理函数直接注册到了被选中的DOM元素中。 .click() 方法只是.bind() 方法的简写。 */ $( "#members li a" ).bind( "click", function( e ) {} ); $( "#members li a" ).click( function( e ) {} );
.bind() method will connect the event handler function to all matching a tags. This approach is not good. In doing so, not only does it implicitly iterate the additional event handlers across all matching elements, but this operation is very wasteful (redundant) because these same event handlers are being added over and over again to all matching tags. superior.
Advantages:
Suitable for various browsers
It is very convenient and fast to connect the event processing function
You can use .click(), .hover() and other shorthand methods to connect the event processing function more conveniently
For a simple ID selector, use The .bind() method can not only quickly connect the event processing function, but also when the event is triggered, the event processing function is called almost immediately
Disadvantages:
This method will attach all event handlers to all matching elements
You cannot dynamically match elements with the same selector
There will be performance problems when operating a large number of matching elements
The append operation is completed in the early stage, which may cause performance problems when the page is loaded
Using the Live method
. The live() method uses the concept of event delegation to implement its so-called "magic". You call the live() method just as easily as you call the bind() method. However, beneath the surface, the .live() method is implemented very differently from the former. The .live() method attaches the selector and event information associated with the event handler to the root element of the document (i.e. document). By registering event information on the document, this event handler will allow all events that bubble up to the document to call it (e.g. delegated, propagated events). Once an event bubbles to the document element, JQuery will use the selector or event metadata to determine which event handler should be called, if one exists. This extra work will have a certain impact on performance during user interaction, but the initial process of registering events is quite fast.
/* 方法将与事件处理函数关联的选择器和事件信息一起附加到文档的根级元素(即document) ( "#members li a" & "click" ) */ $( "#members li a" ).live( "click", function( e ) {} );
.bind() An advantage of this example compared to the bind() method example above is that it only attaches the event handler to the document element once, rather than many times. Not only is this faster, but it also reduces wasted performance. However, using this method also brings many problems, which are listed below.
Advantages:
All event handling functions will only be registered once, instead of multiple registrations like bind()
It is very convenient to upgrade the bind() method to the live() method, you only need to replace "bind" with "live"
Those that are dynamically added Elements to the DOM will also be magically matched, because the real event information is registered on the document element
You can connect the event handler function before the document is loaded, so Can help you make better use of your potentially useless time
Disadvantages:
This method is deprecated in Jquery 1.7 and later versions , you should gradually give up using it in your code
Chain operations are not correctly supported when using this method, and some errors may occur
The matching operation is basically useless because it is only used to register the event handler function on the document element
Using the event.stopPropogation() method will not Used because events are always delegated to the document element
因为所有的选择器或者事件信息都被附加到document元素上了,所以一旦有一个事件要调用某个事件处理函数,Jquery会在一大堆储存的元数据中使用matchesSelector方法来决定哪一个事件处理函数将会被调用,如果这个函数有的话。
因为你所连接的事件总是被委托到document上,所如果你的DOM的层级很深的话,这会导致一定的性能问题
使用Delegate方法
.delegate()方法与live()方式实现方式相类似,它不是将选择器或者事件信息附加到document,而是让你指定附加的元素。就像是live()方法一样,这个方法使用事件委托来正确地工作。
如果你跳过了前面关于 .live() 方法的介绍,你可能要回去重新看看它,因为这里涉及到之前我所阐述的一些内部逻辑
/* .delegate() 方法会将选择器和事件信息 ( "li a" & "click" ) 附加到你指定的元素上 ( "#members" )。 */ $( "#members" ).delegate( "li a", "click", function( e ) {} );
.delegate()方法十分强大。在上面这个例子中,与事件处理函数关联的选择器和事件信息将会被附加到( #members" )这个元素上。这样做比使用live()高效多了,因为live()方法总是将与事件处理函数关联的选择器和事件信息附加到document元素上。另外,使用.delegate()方法解决许多其他问题。请参阅下方列出的详细信息。
优点:
你可以选择将选择器或者事件信息附加到指定的元素。
匹配操作实际上在前面并没有执行,而是用来注册到指定的元素。
链式操作可以得到正确的支持
Jquery仍然需要迭代这些选择器或者事件信息来匹配元素,不过因为你可以选择哪一个元素作为根元素,所以筛选的量会大幅减少
因为这项技术使用了事件委托机制,它可以匹配到被动态地添加到DOM的元素
你可以在文档加载完之前连接事件处理函数
缺点:
从.bind()方法不可以直接升级到.delegate()方法
Jquery仍然需要使用marchesSelector方法在附加到指定根元素的选择器或者事件信息中筛选决定哪一个事件处理函数会被调用。然而,附加到指定根元素的元数据会比使用live()方法的时候要小得多。
当操作大量匹配的元素时会有性能方面的问题
附加操作是在前期完成的,这可能导致页面加载时存在性能问题
使用On方法
你知道吗,在Jquery 1.7版本中.bind() , .live() 和.delegate()方法只需要使用.on()方法一种方式来调用它们。当然.unbind() , .die() 和.undelegate()方法也一样。一下代码片段是从Jquery 1.7版本的源码中截取出来的
bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { return arguments.length == 1 ? this.off( selector, "**" ) : this.off( types, selector, fn ); }
考虑到这一点,使用.on()方法看起来像以下方式一样...
/* Jquery的 .bind() , .live() 和 .delegate() 方法只需要使用`.on()`方法一种方式来调用它们 */ // Bind $( "#members li a" ).on( "click", function( e ) {} ); $( "#members li a" ).bind( "click", function( e ) {} ); // Live $( document ).on( "click", "#members li a", function( e ) {} ); $( "#members li a" ).live( "click", function( e ) {} ); // Delegate $( "#members" ).on( "click", "li a", function( e ) {} ); $( "#members" ).delegate( "li a", "click", function( e ) {} );
你可能注意到了,我如何使用.on()方法决定了它如何调用其他方法。你可以认为.on()方法被具有不同签名的方法”重载“了,而这些方法实现了不同的事件绑定的连接方式。 .on()方法的出现为API带来了很多方面的一致性,并希望让事情变得不那么混乱。
优点:
使各种事件绑定方法一致。
因为在Jquery源码中.bind() , .live() 和.delegate()方法实际上是调用了此方法,因此简化了jQuery代码库并删除了一级重定向。
这种方式仍然提供了使用.delegate()方法的优点,并且仍然提供对.bind()方法的支持,如果你需要的话。
缺点:
给人带来了一些疑惑,因为方法的实际执行方式将根据你如何调用方法而改变。
总结
如果你对不同的绑定事件方法有所迷惑,那么不要担心,因为API发展了一段时间了,有很多前人的经验可以借鉴。也有很多人将这些方法视为魔法,不过一旦你了解了他们工作背后的原理,将帮助您了解如何更好地处理项目。
以下是这篇文章的精华所在...
使用.bind()方法非常浪费性能因为它把同一个事件处理函数附加到了每一个匹配的元素上
你应该停止使用.live()方法因为它被弃用了同时也会带来很多问题
使用.delegate()方法会给你带来很多好处当你需要解决一些性能上的问题和对动态添加的元素作出处理
新的.on()方法其实就是模拟.bind() , .live() 和.delegate()实现的语法糖,具体取决于你如何调用它
新的方向是使用新的.on()方法。先熟悉语法,并开始在你的所有的Jquery 1.7版本以上的项目使用它吧!
Do you have anything new to add to the advantages or disadvantages listed above? Have you started using the delegate() method recently? What do you think of the new .on() method? Let me know your thoughts in the comments! Thanks!
Related recommendations:
jQuery.on() function usage details
jQuery.on() function usage examples
jQuery event binding.on() brief overview and application_jquery
The above is the detailed content of Sharing examples of the differences between .bind(), .live(), .delegate() and .on() in Jquery. For more information, please follow other related articles on the PHP Chinese website!