search
HomeWeb Front-endJS TutorialSharing 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.



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!

Statement
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
Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

See all articles

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function