1. DOM event model

Question: Which function is called first when hello is clicked?

<div class=yeye> <div class=baba> <div class=erzi> Hello </div> </div> </div> </div> </divCopy the code
  • If a function is called from the inside out, it is called event bubbling
  • If a function is called from the outside in order, it is called event capture

In 2002, THE W3C issued a standard stating that browsers should support both call sequences, first from outside in order, and then from inside out order, when there are listening functions to call, and provide event information, not skipped. When an event occurs, it propagates between child and parent elements

Event propagation mechanism

Event propagation mechanism: capture phase – target phase – bubble phase

window ->document ->HTML ->body ->outer ->inner ->center

When an element receives an event, it passes the event to its parent, all the way up to the window. If the parent does not have an event function attached, then it does not behave.

Bind event API

AddEventListener div1.adDeventListener ('click',fn,bool).stopPropagationCopy the code

DOM0

Bound methods are executed in the target or bubble phase

If bool is not passed or falsy, fn executes in the bubbling phase

DOM2

You can control execution during the capture phase

If bool is true, fn executes during the capture phase

A special case

Only one div is listened for (regardless of both parent and child), and any element the user clicks on is listened for by the developer

div.addEventListener('click',f1)
div.addEventListner('click',f2,true)
Copy the code

In this case, f1 is executed first, and whoever listens first is executed.

Event delegation

Delegate the response event (click, keyDown) that needs to be bound to the child element to the parent, which acts as the event listener. Event brokers work by bubbling events from DOM elements.

  • advantages
  1. Save listening (memory) : save a lot of memory
<ul id="list">
 <li>item1</li>
 <li>item2</li>
 <li>item3</li>
 ...
 <li>itemx</li>
</ul>
Copy the code

All click events can be brokered on ul

  1. Elements can be listened on the fly: new child objects are implemented without binding them again

In the above example, adding or subtracting item does not affect the click to be monitored.