1. What is event delegation?Event delegation: Utilize the characteristics of event bubbling to register the processing events that should be registered on the child elements on the parent element. In this way, when the child element is clicked and it is found that there is no corresponding event of itself, the parent element will be searched for and responded to. The advantages of doing this are:
2. The principle of event delegation Event delegation is implemented using the event bubbling principle. What is event bubbling? That is, the event starts from the deepest node and then propagates upward step by step. 3. Implementation of event delegation Implement event delegation through a case. Structure layer + style layer code: <style> * { margin: 0; padding: 0; } ul { float: left; width: 800px; margin-top: 50px; } ul li { list-style: none; float: left; width: 200px; height: 200px; border: 1px solid #000; margin-right: 20px; } ul li:first-child { margin-left: 20px; } </style> <body> <ul id="list"> <li>1</li> <li>2</li> <li>3</li> </ul> </body> 3.1 Method 1: Looping to add eventsDo not use event delegation, use a for loop to add click events, and the memory consumption is large. var oList = document.getElementById('list'); var lis = oList.getElementsByTagName('li'); for (var i = 0; i < lis.length; i++) { lis[i].onclick = function () { this.style.backgroundColor = 'red'; } } 3.2 Method 2: Using event delegationUse event delegation. var oList = document.getElementById('list'); oList.onclick = function (e) { e.target.style.backgroundColor = 'red'; } In this case, e.target represents the element that the user actually clicked. This concludes this article about the detailed process of adding event listeners to event delegation in batches using JavaScript. For more relevant JavaScript event delegation content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Docker build PHP environment tutorial detailed explanation
>>: HTML table markup tutorial (16): title horizontal alignment attribute ALIGN
Preface The latest version of MySQL 8.0 is 8.0.4 ...
Solution: Just set the link's target attribute...
Today I experimented with the network settings un...
Table of contents Preface Option 1: Option 2: Opt...
1. Experimental Environment serial number project...
This article example shares the specific code of ...
mysql 8.0.22 winx64 installation and configuratio...
1. Meaning of partition table A partition table d...
Analyze four common methods and principles: float...
If you upgrade in a formal environment, please ba...
How to install MySQL 5.7 in Ubuntu 16.04? Install...
This article shares the specific code of js to ac...
The GtkTreeView component is an advanced componen...
This article example shares the specific code of ...
Table of contents Problem Description Cause Analy...