define

Since the bubbling phase of the event propagates from bottom to top, the listener function of the child node can be defined on the upper node, and the listener function of the upper node can uniformly process the events of multiple child elements. This is called event delegation.

For example, it can be understood that there are many children to play at home during the summer vacation. If they are allowed to buy bread one by one, it will be inconvenient. The best way is to entrust one parent to buy the bread, and then come back and distribute it to different children according to their needs.

advantages

You don’t have to assign a listener to each element — you put individual listeners on their common upper node. Reduce memory consumption and improve performance.

<ul id="list">
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>.<li>item 99</li>
</ul>
Copy the code
var ul = document.querySelector('ul');

ul.addEventListener('click'.function (event) {
  if (event.target.tagName.toLowerCase() === 'li') {
    alert('li')}});Copy the code

If there are many LI elements in the list, one by one listening will consume a lot of resources. You can use event delegate to define listener functions on the upper node and process the events of the child nodes.