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://m.miracleart.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)

Hot Topics









PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.

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'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.

The difference between var, let and const is scope, promotion and repeated declarations. 1.var is the function scope, with variable promotion, allowing repeated declarations; 2.let is the block-level scope, with temporary dead zones, and repeated declarations are not allowed; 3.const is also the block-level scope, and must be assigned immediately, and cannot be reassigned, but the internal value of the reference type can be modified. Use const first, use let when changing variables, and avoid using var.
