Core points
on()
can be used to implement event delegate, and the optional second parameter specifies the selector for delegate event handler. Then use the event.target
attribute to identify which element triggered the event. 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:
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="https://www.php.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:
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 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.
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.
.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.
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.
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.
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.
.bind()
methods used for event processing in jQuery? .on()
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()
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.
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!