Event delegation makes use of the event bubbling principle to let the parent of a node execute events on its behalf. You don’t need to loop through the element’s children

Advantages,

√ Number of listeners saved (memory)

√ can listen for dynamic elements

One scenario,

If you want to add click events to 100 buttons, what do you do?

A: Listen for the parent of the 100 buttons and wait for bubbles to determine if the value of event. Target is one of the 100 buttons

Scenario 2,

You want to listen for click events for elements that do not currently exist.

A: Listen on the parent, wait for the click to see if you want to listen to the element

Envent. target: envent.target: envent.target: envent.target: envent.target: envent.target: envent.target: envent.target: envent.target: envent.target: envent.target


<html>
<head>
  <meta charset="utf-8">
  <title>title</title>
</head>
<body>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
 <script>
    on('click'.'ul'.'li'.() = >{
       console.log('Li was clicked')})function on(eventType,element,selector,fn){
      if(! (elementinstanceof Element)){
      // If checks whether the element passed in is an Element, or if it is an ID or class name, gets the element with the corresponding name
          element=document.querySelector(element)
      }
      element.addEventListener(eventType,(e) = >{
          const t=e.target
          if(t.matches(selector)){ // maches checks whether the selectors match
          return fn(e)
          }
   })
}
 </script>
</body>
</html>

Copy the code

Scenario 3,

< span > < span > < span > < span > < span > < span >

Solution: in this case, the parent node should be traversed to see if there is li until ul is traversed. Example:


<html>
<head>
  <meta charset="utf-8">
  <title>title</title>
</head>
<body>
    <ul>
        <li>1</li>
        <li><span>2</span></li>
        <li>3</li>
    </ul>
 <script>
    function on(eventType,element,selector,fn){
      element.addEventListener(eventType,e= >{
        let el=e.target
        // maches checks whether the selectors match
        while(! el.matches(selector)){There is no target element if the parent element is traversed all the way to the event delegate element
          if(el===element){
            el=null // make el null to end the loop
            break
          }
          el=el.parentNode
        }
        //el is not empty to execute fn
        el&&fn.call(el,e,el)
      })
      return element
    }
    on('click'.'ul'.'li'.(e) = >{console.log(e.target.innerHTML)})
 </script>
</body>
</html>

Copy the code