Home >Web Front-end >Front-end Q&A >What is javascript event delegation
In JavaScript, event delegation uses the principle of bubbling to add events to parent elements or ancestor elements to trigger execution effects. The advantages of event delegation: 1. It can improve JS performance; 2. It can dynamically add DOM elements without modifying event bindings due to changes in elements.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
1. What is event delegation?
#Event delegation uses the principle of bubbling to add events to parent elements or ancestor elements to trigger execution effects.
Example: Bind the click event in the document. When the click object is the button btn, the pop-up box displays the value of the button btn
<body> <button id="btn" value="嘿嘿">哈哈</button> <script> window.onload=function () { let btn=document.getElementById("btn") document.onclick=function (e) { // console.log(e.target) if(e.target===btn){ alert(btn.value) } } } </script> </body>
2. Advantages of event delegation
#(1) Can improve JS performance
Example: Create on ul 100 li, click on each li and a pop-up box will display the value of the li
Traditional writing method: bind the onclick event to each li and trigger the alert event
Event delegation: Bind the onclick event on the document. When the onclick event is triggered, determine whether it is a
(2) DOM elements can be added dynamically, and there is no need to modify event bindings due to changes in elements.
3. Things to note about event delegation
The element to which the event delegation is bound should preferably be the parent of the element being monitored Elements, such as
The above is the detailed content of What is javascript event delegation. For more information, please follow other related articles on the PHP Chinese website!