Home Web Front-end JS Tutorial Sharing examples of the differences between .bind(), .live(), .delegate() and .on() in Jquery

Sharing examples of the differences between .bind(), .live(), .delegate() and .on() in Jquery

Dec 31, 2017 am 09:44 AM
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>
Copy after login

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 ) {} );
Copy after login

.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 ) {} );
Copy after login

.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 ) {} );
Copy after login

.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 );
}
Copy after login

考虑到这一点,使用.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 ) {} );
Copy after login

你可能注意到了,我如何使用.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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

In-depth analysis: jQuery's advantages and disadvantages In-depth analysis: jQuery's advantages and disadvantages Feb 27, 2024 pm 05:18 PM

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

See all articles