Core points
- Event delegates in jQuery are a technique for attaching a single event handler to a parent element instead of multiple handlers attached to individual elements, thereby reducing memory usage and improving performance.
- jQuery function
on()
can be used to implement event delegate, and the optional second parameter specifies the selector for delegate event handler. Then use theevent.target
attribute to identify which element triggered the event. - In dynamic applications, elements are often added or removed, and event delegates are especially useful because it eliminates the need to manage events manually and reduces code complexity. However, it should be noted that the sub-event handler handles before delegating the event handler and may prevent the event from propagating.
jQuery simplifies event handling in JavaScript. However, the more event handlers are defined, the more memory is used, which will eventually lead to performance degradation and slow down the UI. This article explores how event delegates can help prevent this, and how event delegates can be applied in jQuery. Event delegates are an event processing technique that instead of appending an event handler directly to each element that is to listen for an event, it appends a single event handler to the parent element of these elements to listen for happening on its child elements. events. When processing an event, check which element triggers the event and responds accordingly. Event delegates depend on event bubbles in the DOM. This is the process of events triggered on children propagating up to the DOM tree to its parent element and its parent element, etc. until it reaches the document. Programmers can use event.stopPropagation()
to stop bubbling. Note that not all DOM events will propagate—focus, blur, load, and unload will not. Event delegates use less memory because you replace multiple event handlers with a single event handler. For example, if you attach an event handler to each link in the list of ten links, there will be ten event handlers taking up memory space. Instead, if you use event delegates and handle events at the parent element, only one event handler is created and less memory is used than the memory attached to each link separately. In addition to reducing memory consumption, event delegation also has the following advantages:
- No need to manually manage events when adding elements to or removing elements from DOM. If we use traditional event handling, we must attach the event handler to the element added to the DOM and remove the event handler from the element removed from the DOM.
- Reduce the code to be managed with fewer event handlers. This can make our code simpler without any duplicate event handling logic, which helps keep our JavaScript concise and DRY.
Example of event delegation in jQuery
Suppose you are developing a single page application that sells kitten pictures. When the page loads, the top 20 kittens will be displayed. When the user scrolls down the page, more kittens will be loaded. Our HTML looks like this:
<div id="cats"> <ul> <li> <img src="/static/imghw/default1.png" data-src="https://img.php.cn/" class="lazy" alt=""/> <a href="http://ipnx.cn/link/207f170979dd72ff5776e20d07c28732">More info</a> <button>Add to cart</button> </li> ... </ul> </div>
Using traditional event handling, we need to connect the event handler to:
- A larger image is displayed when the user clicks on the thumbnail.
- More information is displayed when the user clicks the "More Information" link.
- Add the image to the cart when the user clicks "Add to Cart".
- Attach these three events to the new DOM element added when the user scrolls down the page.
This code will be similar to the following example. Note that this is intended to show how appending an event handler to individual elements differs from using event delegates, so there is no implementation provided for loadImage()
, moreInfo()
, addToCart()
, and loadNewKittens()
functions.
$(document).ready(function() { var cats = $('#cats'); cats.find('img') .on('click', function() { loadImage(); }) cats.find('a') .on('click', function(event) { event.preventDefault(); moreInfo(); }); cats.find('button') .on('click', function() { addToCart(); }); $(window).scroll(function() { var fragment = loadNewKittens(); // 為新的DOM元素附加事件處理程序 fragment.find('img') .on('click', function() { loadImage(); }); fragment.find('a') .on('click', function(event) { event.preventDefault(); moreInfo(); }); fragment.find('button') .on('click', function() { addToCart(); }); fragment.appendTo('#cats ul'); }); });
The code volume is quite large. Now let's see what our code looks like if we use event delegates:
$(document).ready(function() { $('#cats') .on('click', 'img, a, button', function(event) { event.preventDefault(); var target = event.target; switch(target.tagName.toLowerCase()) { case 'img': loadImage(); break; case 'a': moreInfo(); break; case 'button': addToCart(); break; default: // 什么也不做 } }); $(window).scroll(function() { var fragment = loadNewKittens(); fragment.appendTo('#cats ul'); }); });
The key lies in the optional second parameter of on()
. By passing the selector here, on()
knows that it is handling the delegate event handler instead of the directly bound event handler. Our event handling code is much simpler now. By getting event.target
and switching based on its tagName
, we can determine which element triggered the event and respond accordingly. Additionally, we no longer need to attach event handlers to elements loaded in $(window).scroll
, because events triggered by these new elements are delegated to the parent element. A potential "trap" to be noted when using event delegates is that any event handler attached to a child element is handled before the delegate event handler triggers . Therefore, the sub-event handler may call or return event.stopPropagation()
, which will prevent the event from bubbled into the delegate event handler and leave you puzzled as to why your event is not delegated. false
Conclusion
In this article, we study event delegation. We've seen how it can help improve the performance of a website by reducing the event processing load it has to bear. We also saw how to implement event delegate in jQuery through the function. on()
Frequently Asked Questions about jQuery Event Delegation
What is event delegate in jQuery and why it matters?Event delegates in jQuery are a technique that allows you to attach a single event listener to the parent element, which will fire for all descendants of matching selectors, whether those descendants exist now or are added in the future. This is important because it can greatly improve performance by reducing the number of event handlers required by the application. Instead of appending individual event handlers to each element, you can delegate events to parent elements. This is especially useful in dynamic applications where elements are added or removed dynamically.
How does event delegation work in jQuery?
Event delegates in jQuery take advantage of the fact that most jQuery events will bubble or propagate up to the DOM tree. When an event is fired on a child element, it will bubble to its parent element. By appending an event listener to the parent element, you can capture events triggered on any of its child elements. The event.target
attribute can be used to determine which child element triggered the event.
What is the difference between direct events and delegated events in jQuery?
Direct events are directly attached to specific elements, and only these elements can trigger events. On the other hand, delegate events are attached to the parent element, and any child element can trigger events. The advantage of delegate events is that they can handle events of dynamically added child elements.
How to use the .on()
method to perform event delegation in jQuery?
The .on()
method in jQuery is used to attach event handlers. For event delegates, you will use three parameters: event type, selector string used to filter descendants, and handler functions. An event type is a string representing the event type (for example, "click"), a selector string is used to filter descendants of the selected element that triggers the event, and a handler function is a function to be executed when the event is triggered.
Can I use event delegate to handle dynamically added elements in jQuery?
Yes, one of the main advantages of event delegates in jQuery is that it can handle events of elements that are dynamically added. Since the event listener is attached to the parent element, it can capture events triggered on any of its child elements, even if those events are added after the event listener is attached.
What is event bubble, and what does it have to do with event delegation in jQuery?
Event bubble is an event propagation type in which an event starts with the specific element that triggers it and then bubbles to its ancestors. Event delegates in jQuery use event bubbles to attach event listeners to parent elements. When an event is fired on a child element, it will bubble to the parent element, where the event listener can capture it.
How to stop event propagation in jQuery?
You can use the .stopPropagation()
method to stop event propagation in jQuery. This method prevents events from bubbled into the DOM tree, thus preventing any parent handler from receiving event notifications. However, you should use it with caution as it will make your code harder to debug and understand.
and .bind()
methods used for event processing in jQuery? .on()
The method in jQuery is used to attach an event handler directly to an element. On the other hand, the .bind()
method can be used to attach an event handler directly to an element (such as .on()
) or to a parent element for event delegating. The .bind()
method is more general and is the preferred method for attaching event handlers in jQuery. .on()
Can I use event delegate to handle custom events in jQuery?
Yes, you can use event delegate to handle custom events in jQuery. Like standard events, you can attach an event listener to a parent element, which will capture custom events triggered on any of its children.
How to delete event handler in jQuery?
You can use the .off()
method to delete the event handler in jQuery. This method can be used to delete all event handlers on an element, or to delete only event handlers with a specific event type or namespace attached.
The above is the detailed content of Event Delegation with jQuery. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

IIFE (ImmediatelyInvokedFunctionExpression) is a function expression executed immediately after definition, used to isolate variables and avoid contaminating global scope. It is called by wrapping the function in parentheses to make it an expression and a pair of brackets immediately followed by it, such as (function(){/code/})();. Its core uses include: 1. Avoid variable conflicts and prevent duplication of naming between multiple scripts; 2. Create a private scope to make the internal variables invisible; 3. Modular code to facilitate initialization without exposing too many variables. Common writing methods include versions passed with parameters and versions of ES6 arrow function, but note that expressions and ties must be used.

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.
