Imagine that if you have an unordered list with a bunch of <li> elements, each <li> element triggers an action when you click. At this time, you usually add an event listener to each element. But if this element or the object you added to the listener is frequently removed and added? At this time, you need to handle the removal and addition of event listening when removing the add element. At this time, we need to introduce event delegation.
Event delegation adds an event listener to a parent element instead of an event listener to each child element. When an event is triggered, event.tar get evaluates whether the action needs to be executed. The following is a simple example:
// Obtain the element and add event listening
Document. querySelector ('# parent-list'). addEventListener ('click', function (e ){
// E.tar get is a clicked element!
// If it is a list element
If(e.tar get & e.tar get. tagName = 'lil '){
// We have found this element and can write its operations here.
}
});
The above example is incredibly simple. when an event occurs, it does not poll the parent node to find the matching element or selector, it does not support selector-based queries (for example, using class name or id ). All JavaScript frameworks provide Delegate selector matching. The point is that you do not need to load event listening for every element, but add a event listening to the parent element. This greatly increases efficiency and reduces maintenance!