Home > Web Front-end > JS Tutorial > Technical principles of JavaScript event delegation

Technical principles of JavaScript event delegation

coldplay.xixi
Release: 2020-06-17 16:08:54
forward
2345 people have browsed it

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>
Copy after login

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!");
	}
});
Copy after login

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

				}
			}
		}

	}
});
Copy after login

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!

Related labels:
source:webhek.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template