search
HomeWeb Front-endJS TutorialjQuery event binding and delegate examples_jquery

The examples in this article describe jQuery event binding and delegation. Share it with everyone for your reference. The specific method is as follows:

JQuery event binding and delegation can be implemented using a variety of methods, on() , bind() , live() , delegate() , and one().

Sometimes we may bind an event like this:

Copy code The code is as follows:
$("#div1").click(function() {
alert("Trigger after click");
});

We can implement the above event binding in a variety of ways:

1. on()

Copy code The code is as follows:
//No data parameters
$("p").on("click", function(){
alert( $(this).text() );
});

//There are data parameters
function myHandler(event) {
alert(event.data.foo);
}
$("p").on("click", {foo: "bar"}, myHandler)

Corresponding to on() is off(), which is used to remove event binding:

Copy code The code is as follows:
var foo = function () {
// code to handle some kind of event
};
// ... now foo will be called when paragraphs are clicked ...
$("body").on("click", "p", foo);

// ... foo will no longer be called.
$("body").off("click", "p", foo);

off(): remove the binding by on()
one(): only bind once.

2. bind()

Parameters:
(type,[data],function(eventObject))
type: A string containing one or more event types, with multiple events separated by spaces. For example, "click" or "submit", or a custom event name.
data: Additional data object passed to the event object as the event.data attribute value

fn: The handler function bound to the event of each matching element

(type,[data],false)
type: A string containing one or more event types, with multiple events separated by spaces. For example, "click" or "submit", or a custom event name.
data: Additional data object passed to the event object as the event.data attribute value

false: Setting the third parameter to false disables the default action.

Bind multiple event types at the same time:

Copy code The code is as follows:
$('#foo').bind('mouseenter mouseleave', function() {
$(this).toggleClass('entered');
});

Bind multiple event types/handlers simultaneously:

Copy code The code is as follows:
$("button").bind({
click:function(){$("p").slideToggle();},
mouseover:function(){$("body").css("background-color","red");},
mouseout:function(){$("body").css("background-color","#FFFFFF");}
});

You can pass some additional data before event handling.

Copy code The code is as follows:
function handler(event) {
alert(event.data.foo);
}
$("p").bind("click", {foo: "bar"}, handler)


Cancel the default behavior and prevent the event from bubbling by returning false.

Copy code The code is as follows:
$("form").bind("submit", function() { return false; })

Problems with bind

If there are 10 columns and 500 rows in the table to which click events are bound, then finding and traversing 5000 cells will cause the script execution speed to slow down significantly, and saving 5000 td elements and corresponding event handlers will also Takes up a lot of memory (similar to having everyone physically stand at the door waiting for a delivery).

Based on the previous example, if we want to implement a simple photo album application, each page only displays thumbnails of 50 photos (50 cells), and the user clicks "Page x" (or "Next Page") link can dynamically load another 50 photos from the server via Ajax. In this case, it seems that binding events for 50 cells using the .bind() method is acceptable again.

This is not the case. Using the .bind() method will only bind click events to 50 cells on the first page. Cells in subsequent pages that are dynamically loaded will not have this click event. In other words, .bind() can only bind events to elements that already exist when it is called, and cannot bind events to elements that will be added in the future (similar to how new employees cannot receive express delivery).

Event delegation can solve the above two problems. Specific to the code, just use the .live() method newly added in jQuery 1.3 instead of the .bind() method:

Copy code The code is as follows:
$("#info_table td").live("click",function() {/*Show more information*/});

The .live() method here will bind the click event to the $(document) object (but this cannot be reflected from the code. This is also an important reason why the .live() method has been criticized. We will discuss it in detail later. ), and you only need to bind $(document) once (not 50 times, let alone 5000 times), and then you can handle the click event of the subsequent dynamically loaded photo cell. When receiving any event, the $(document) object will check the event type and event target. If it is a click event and the event target is td, then the handler delegated to it will be executed.

unbind(): Removes the binding performed by bind.

3. live()

So far, everything seems perfect. Unfortunately, this is not the case. Because the .live() method is not perfect, it has the following major shortcomings:
The $() function will find all td elements in the current page and create jQuery objects. However, this td element collection is not used when confirming the event target. Instead, a selector expression is used to compare with event.target or its ancestor elements, so Generating this jQuery object will cause unnecessary overhead;
By default, events are bound to the $(document) element. If the DOM nested structure is very deep, events bubbling through a large number of ancestor elements will cause performance losses;
It can only be placed after the directly selected element, and cannot be used after the consecutive DOM traversal method, that is, $("#info_table td").live... can be used, but $("#info_table").find("td" ).live...No;
Collect td elements and create jQuery objects, but the actual operation is the $(document) object, which is puzzling.
The solution
To avoid generating unnecessary jQuery objects, you can use a hack called "early delegation", which is to call .live() outside the $(document).ready() method:

Copy code The code is as follows:
(function($){
$("#info_table td").live("click",function(){/*Show more information*/});
})(jQuery);

Here, (function($){...})(jQuery) is an "anonymous function that is executed immediately", forming a closure to prevent naming conflicts. Inside the anonymous function, the $parameter refers to the jQuery object. This anonymous function does not wait until the DOM is ready before executing. Note that when using this hack, the script must be linked and/or executed in the head element of the page. The reason for choosing this timing is that the document element is available at this time, and the entire DOM is far from being generated; if the script is placed in front of the closing body tag, it makes no sense, because the DOM is fully available at that time.

In order to avoid performance losses caused by event bubbling, jQuery supports the use of a context parameter when using the .live() method starting from 1.4:

Copy code The code is as follows:
$("td",$("#info_table")[0]). live("click",function(){/*Show more information*/});

In this way, the "trustee" changes from the default $(document) to $("#info_table")[0], saving the bubbling trip. However, the context parameter used with .live() must be a separate DOM element, so the context object is specified here using $("#info_table")[0], which is obtained using the array index operator. A DOM element.

4. delegate()

As mentioned earlier, in order to break through the limitations of the single .bind() method and implement event delegation, jQuery 1.3 introduced the .live() method. Later, in order to solve the problem of too long "event propagation chain", jQuery 1.4 supported specifying context objects for the .live() method. In order to solve the problem of unnecessary generation of element collections, jQuery 1.4.2 simply introduced a new method.delegate().

Using .delegate(), the previous example can be written like this:

Copy code The code is as follows:
$("#info_table").delegate("td","click", function(){/*Show more information*/});

Using .delegate() has the following advantages (or solves the following problems of the .live() method):
Directly bind the target element selector ("td"), event ("click") and handler to the "dragee" $("#info_table"), without additional collection of elements, shortened event propagation path, and clear semantics;

Supports calling after the consecutive DOM traversal method, that is, supports $("table").find("#info").delegate..., supporting precise control;

It can be seen that the .delegate() method is a relatively perfect solution. But when the DOM structure is simple, .live() can also be used.

Tip: When using event delegation, if other event handlers registered on the target element use .stopPropagation() to prevent event propagation, the event delegation will become invalid.

undelegate(): Remove the binding of delegate

I hope this article will be helpful to everyone’s jQuery programming.

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
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.