Technical principles of JavaScript event delegation
One of the hottest technologies in today’s JavaScript technology world should be ‘event delegation’. Using event delegation techniques allows you to avoid adding event listeners to specific each node; instead, event listeners are added to their parent elements. The event listener will analyze the events that bubble up from the child elements and find out which child element the event is from. The basic concept is very simple, but there are still many people who don't understand how event delegation works. Here I'm going to explain how event delegation works and provide a few examples of basic event delegation in pure JavaScript.
Suppose we have a UL
element with several sub-elements:
<ul id="parent-list"> <li id="post-1">Item 1</li> <li id="post-2">Item 2</li> <li id="post-3">Item 3</li> <li id="post-4">Item 4</li> <li id="post-5">Item 5</li> <li id="post-6">Item 6</li> </ul>
We also assume that when each sub-element is clicked, there will be a different event occurs. You can add event listeners to each independent li
element, but sometimes these li
elements may be deleted or added, and listen for their new or deleted events. This can be a nightmare, especially if your event-listening code is in another part of your application. But what if you place listeners on their parent elements? How do you know which child element was clicked?
Simple: When a child element's event bubbles up to the parent ul
element, you can check the target property of the event object to capture a reference to the node element that was actually clicked. The following is a very simple JavaScript code that demonstrates the process of event delegation:
// 找到父元素,添加监听器... document.getElementById("parent-list").addEventListener("click",function(e) { // e.target是被点击的元素! // 如果被点击的是li元素 if(e.target && e.target.nodeName == "LI") { // 找到目标,输出ID! console.log("List item ",e.target.id.replace("post-")," was clicked!"); } });
The first step is to add an event listener to the parent element. When an event triggers the listener, check the source of the event and exclude non-li
child element events. If it is a li
element, we have found the target! If not a li
element, the event will be ignored. This example is very simple, UL
and li
are standard parent-child combinations. Let's experiment with some different combinations of elements. Suppose we have a parent element p
, which has many child elements, but what we care about is the A tag with the "classA" CSS class inside:
// 获得父元素p, 添加监听器... document.getElementById("myp").addEventListener("click",function(e) { // e.target是被点击的元素 if(e.target && e.target.nodeName == "A") { // 获得CSS类名 var classes = e.target.className.split(" "); // 搜索匹配! if(classes) { // For every CSS class the element has... for(var x = 0; x < classes.length; x++) { // If it has the CSS class we want... if(classes[x] == "classA") { // Bingo! console.log("Anchor element clicked!"); // Now do something here.... } } } } });
In the above example Not only the tag names are compared, but also the CSS class names. Although it is a little more complicated, it is still very representative. For example, if there is a span
tag in an A tag, this span
will become the target element. At this time, we need to trace up the DOM tree structure to find out whether there is an A.classA element in it.
Because most programmers will use tool libraries such as jQuery to handle DOM elements and events, I recommend that everyone use the event delegation method inside, because the tool library here provides advanced delegation methods and element screening. method.
I hope this article can help you understand the behind-the-scenes principles of JavaScript event delegation, and I hope you also feel the powerful use of event delegation!
(English: davidwalsh.)
Recommended tutorial: "javascript basic tutorial"
The above is the detailed content of Technical principles of JavaScript event delegation. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

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



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
