search
HomeWeb Front-endJS TutorialIntroduction to four ways to bind events with jQuery

This chapter will introduce you to the four ways of binding events in jQuery. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

jQuery provides four event monitoring methods, namely bind, live, delegate, and on. The corresponding functions to unlisten are unbind, die, undelegate, and off. Let’s give you a detailed introduction one by one through this article. Friends who are interested should take a look together

jQuery provides a variety of ways to bind events. Each method has its own characteristics. Understand the similarities and differences between them. , helps us make correct choices when writing code, so as to write elegant and easy-to-maintain code. Let's take a look at the ways to bind events in jQuery.

jQuery provides four event monitoring methods, namely bind, live, delegate, and on. The corresponding functions to unlisten are unbind, die, undelegate, and off. Before starting to look at them

One: bind(type,[data],function(eventObject))

bind is used more frequently One type, its function is to bind a listening function of a specific event type to the selected element. The meaning of the parameters is as follows:

type: event type, such as click, change, mouseover, etc.;

data: The parameters passed into the listening function are obtained through event.data. Optional;

function: listening function, which can pass in the event object. The event here is the event object encapsulated by jQuery, which is different from the native event object. When using it, you need to pay attention to the

bind Source code:

bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
}
$('#myol li').bind('click',getHtml);

The characteristic of bind is that it will bind the listener to the target element, one to one. There is no problem in using it when the elements on the page will not be added dynamically. But if a "list element 5" is dynamically added to the list, there will be no response when clicking on it, and you must bind it again. To avoid this trouble, we can use live.

jQuery also has a shorthand way of event binding, such as a.click(function(){});, a.change(function(){});, etc. Their functions are the same as bind, only It's just an abbreviation.

2: live(type, [data], fn)

The parameters of live are the same as bind. What’s wrong with it? Let’s take a look at the source code first. :

live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
}

You can see that the live method does not bind the listener to itself (this), but to this.context. What is this context? In fact, it is the limited range of the element. It will be clear after reading the following code:

$('#myol li').context; //document
$('#myol li','#myol').context; //document
$('#myol li',$('#myol')[0]); //ol

Normally, we will not use selectors like the third method. Therefore, it is considered that this context is usually the document, that is, the live method binds the listener to the document. Without binding the listener directly to the element, have you remembered the event delegation mechanism? If not, you can click here to recall it. Live uses the event delegation mechanism to complete event monitoring and processing, and delegates node processing to document. In the listening function, we can use event.currentTarget to obtain the node currently capturing the event. The following example will reveal:

$('#myol li').live('click',getHtml);

3: Live has such shortcomings, so we thought, since the old man has such a heavy burden, can we not bind the listener to the document? On the other hand, wouldn't it be better to bind it to the nearest parent element. Following normal logic, delegate was born.

The parameter has an additional selector, which is used to specify the target element that triggers the event. The listener will be bound to the element that calls this method. Take a look at the source code:

delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
}

calls on again and passes the selector to on. It seems that this on is really important. Just ignore it for now. Let’s take a look at the example first:

$('#myol').delegate('li','click',getHtml);

After reading so much, you can’t wait to see the true face of this on. Here comes:

on(type,[selector],[data],fn)

Parameters and delegates It's almost the same but there are still subtle differences. First, type and selector have changed their positions, and second, selector has become optional. The reason for switching positions is difficult to verify, but it should be to make it more visually comfortable.

Let’s look at an example without passing the selector:

$('#myol li').on('click',getHtml);

You can see that event.currentTarget is li itself, which has the same effect as bind. As for passing the selector in, it has the same meaning as the delegate. Except for the different order of parameters, everything else is exactly the same.

Finally we see the real role of on. So, with so many event binding methods, how should we choose?

In fact, there is no need to worry about this issue at all, because you have already You know the difference between them, right? Just use it according to the actual situation. However, an official recommendation is to use on as much as possible, because other methods are completed by calling on internally. Using on directly can improve efficiency, and you can use on to replace the other three writing methods. As for how to replace them, I think there is no need to write them out so straightforwardly. After truly understanding their differences, it will naturally not be difficult.

The above are the four methods of jQuery binding events introduced by the editor. I hope it will be helpful to everyone.

Statement
This article is reproduced at:脚本之家. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.