This article analyzes the principles and usage of JavaScript event delegation. Share it for your reference, as follows:
In daily life, we may hear the concept of event commission. Some students may already have a good understanding of event commission, and some students may have just heard of event commission and can only use it simply, but they do not know much about the principle of event commission. So this blog post will explain the principle of event delegation in native JS, why there are event delegations, why can event delegation be used in this way, etc.
1. Event flow in js
Before parsing event delegates, we first review the event stream in js, i.e. bubble and capture.
①.Bubbles: When a lower node triggers an event, the event will trigger similar events of the upper node step by step.
②.Capture: Similar to bubble, except that the sequence of events is in the opposite order. That is, it is passed from the upper node to the lower node
2. The principle of event delegation
Event delegates are generated based on js event streams. Event delegates use event bubbles to add events to parent elements or ancestor elements to trigger the event.
<body> <div > <input type="button" value="Button 1" > <input type="button" value="Button 2" > <input type="button" value="Button 3" > </div> </body> <script type="text/javascript"> ("myDiv").onclick=function(e){ e=||e; var btnId=; switch(btnId){ case "btn1": ("Button 1"); break; case "btn2": ("Button 2"); break; case "btn3": ("Button 3"); break; } } </script>
The above code is a typical event delegation case. The principle of use is that event bubbles, loads events on the parent element, and distinguishes the difference between buttons through event parameters.
3. Summary
By observing the above event delegate code, we can easily derive the benefits of event delegate:
①. Reduce the number of page binding events. Since the number of page event bindings is larger, the worse the page execution performance, so event delegation can improve the performance of the page.
②. Event delegation can flexibly handle dynamic changes in child nodes. Event delegation does not need to be rebinded regardless of whether the child nodes increase or decrease.
PS:For javascript events, please refer to this siteA complete list of javascript events and functions:http://tools./table/javascript_event
For more information about JavaScript, readers who are interested in reading this site's special topic:A complete collection of operations and techniques related to JavaScript events》、《Summary of JavaScript page element operation skills》、《Summary of JavaScript DOM skills》、《Summary of JavaScript search algorithm skills》、《Summary of JavaScript data structure and algorithm techniques》、《JavaScript traversal algorithm and skills summary"and"Summary of JavaScript Errors and Debugging Skills》
I hope this article will be helpful to everyone's JavaScript programming.