Home > Article > Web Front-end > How to use JS event delegation in your project
This time I will show you how to use JS event delegation in projects, and what are the precautions for using JS event delegation in projects. The following is a practical case, let's take a look.
In daily life, we may hear the concept of event delegation. Some students may already know a lot about event delegation, and some students may have only heard of event delegation and can use it simply, but for I don’t know much about the principle of event delegation. Therefore, this blog post will explain the principle of event delegation in native js, why there is event delegation, why event delegation can be used in this way, and other issues.
1. Event flow in js
Before parsing the event delegate, we first review the event flow in js, that is, bubbling and capturing.
①. Bubbling: When a lower-level node triggers an event, the event will trigger similar events on the upper-level node step by step.
②. Capture: Similar to bubbling, except that the order of events is reversed. That is, it is passed from the superior node to the subordinate node
2. Principle of event delegation
Event delegation is generated based on the js event stream, and event delegation uses event bubbling , add the event to the parent element or ancestor element to trigger the event.
<body> <p id="myp"> <input type="button" value="按钮1" id="btn1"> <input type="button" value="按钮2" id="btn2"> <input type="button" value="按钮3" id="btn3"> </p> </body> <script type="text/javascript"> document.getElementById("myp").onclick=function(e){ e=window.event||e; var btnId=e.target.id; switch(btnId){ case "btn1": console.log("按钮1"); break; case "btn2": console.log("按钮2"); break; case "btn3": console.log("按钮3"); break; } } </script>
The above code is a typical event delegation case. The principle of utilization is event bubbling, loading the event on the parent element, and distinguishing the buttons through event parameters
3. Summary
By delegating the above event code From the observation, we can easily draw the benefits of event delegation:
①. Reduce the number of page binding events. Since the more page event bindings, the worse the page execution performance, so event delegation can improve the page Performance
②. Event delegation can flexibly handle dynamic changes in child nodes. No matter whether child nodes increase or decrease, events do not need to be re-bound.
I believe you have mastered it after reading the case in this article. For more exciting methods, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Using the webpack refresh parsing function
How to use the Installation plug-in in actual projects
The above is the detailed content of How to use JS event delegation in your project. For more information, please follow other related articles on the PHP Chinese website!