1. Capture and bubble
<div class="Grandpa">
    <div class="Dad">
        <div class="Son">content</div>
    </div>
</div>
Copy the code

Grandpa >. Dad.>. Son, listen on fnYe/fnBa/fnEr respectively. If you click on text, what is the order of the three event listener functions? This is capture if you call grandpa => dad => son, and bubbling if you call son => Dad => Grandpa. That is, looking for listener functions from the outside in, called event capture; Look for the listener function from the inside out, called event bubble.

  1. Event binding API

xxx.addEventListener('click',fn,bool)

  • If bool is not passed or falsy, let fn bubble, that is, when the browser finds that XXX has a FN listener during the bubble phase, fn will be called and event information will be provided.
  • If bool is true, let fn capture.
  1. Event delegation

Since events propagate up to the parent node during the bubbling phase, you can define the listener functions of the child node on the parent node, and let the listener functions of the parent node uniformly handle the events of multiple child elements. This method is called event delegate. Advantages:

  • If you want to add events to 100 buttons, you can listen for the parent element of those 100 buttons, and when it bubbles, determine if target is one of those 100 buttons.
  • You can listen for dynamic elements. If you want to listen for a click on an element that doesn’t exist, you can listen for the parent element and wait until it clicks to see if it’s the element you want to listen for.
let ul = document.querySelector('ul');
ul.addEventListener('click'.function(event)){
    if(event.target.tagName.toLowerCase() === 'li') {//some code}}Copy the code

In the code above, the listener function for the click event is defined in

    Node, but really, it deals with child nodes

  • Click event.