Home >Web Front-end >JS Tutorial >Detailed explanation of the use of event delegation in JS
This time I will bring you a detailed explanation of the use of event delegation in JS. What are the precautions when using event delegation in JS. The following is a practical case, let's take a look.
Event delegation (also called Event proxy), in fact, this problem is also simple. To understand event delegation, we must first understand the event bubbling mechanism. clear. Give an example of event bubbling:
<ul> <li>点击</li> </ul> <script> var ul=document.getElementsByTagName('ul')[0]; var li=document.getElementsByTagName('li')[0]; ul.addEventListener('click', function(){ alert('我是ul,我被点击了'); }, false); li.addEventListener('click', function(){ alert('我是li,我被点击了'); }, false); </script>
In this code, when we click li, the click event of li is triggered, but at this time, the click event of ul is also triggered. This is The bubbling of events. After understanding this, we can talk about event delegation. Since events can bubble up from the parent element (ul) of the child element (li), then we can add a click event to ul itself and combine all li events. All are delegated to our parent (ul). Maybe some friends here still don’t understand the use of this event delegation. Let’s give an example of event delegation to illustrate:
<ul> <li>点击1</li> <li>点击2</li> <li>点击3</li> <li>点击4</li> <li>点击5</li> </ul> <script> //使用事件委托的代码 var ul=document.getElementsByTagName('ul')[0]; ul.addEventListener('click', function(e){ alert(e.target.innerHTML); }, false); //不使用事件委托,循环给li添加click事件 var li=document.getElementsByTagName('li') for(var i=0;i<li.length;i++){ li[i].onclick=function(){ alert(this.innerHTML); } } </script>
We are above The code delegates the event to ul, and only adds click events to ul. When running the corresponding li in the browser, the innerHTML
corresponding to the li will pop up. This function(e){};## The e parameter in # is actually some event information sent to us by the system when we click on the li.
e.target actually refers to the li we click on. Here, every time we click What pops up is the
innerHTML of the currently clicked object. This is a simple case of event delegation.
Detailed explanation of the steps to use WebUploader in the fuzzy box
Detailed explanation of computed use cases in Vue.js
The above is the detailed content of Detailed explanation of the use of event delegation in JS. For more information, please follow other related articles on the PHP Chinese website!