Get the App
SLTechnology News&Howtos  ›  Development  › 

Example Analysis of event Bubble in JavaScript

Shulou Source: shulou.com Published: 2022-06-01 03:46:04 09月22日 Update

This article mainly introduces the example analysis of event bubbling in JavaScript, which is very detailed and has certain reference value. Friends who are interested must finish it!

What is event bubbling?

Event bubbling is the opposite of event capture, the current element-> body-> html---- > document-> window. When an event occurs on a DOM element, the event does not happen exactly on that element. In the bubbling phase, the event bubbles, or the event occurs in its parents, grandparents, grandparents, until it reaches window.

Suppose you have the following HTML structure:

one

Corresponding JS code:

Function addEvent (el, event, callback, isCapture = false) {if (! el | |! event | |! callback | | typeof callback! = = 'function') return; if (typeof el =' string') {el = document.querySelector (el);}; el.addEventListener (event, callback, isCapture);} addEvent (document, 'DOMContentLoaded', () = > {const child = document.querySelector (' .child'); const parent = document.querySelector ('.parent'); const grandparent = document.querySelector ('.grandparent') AddEvent (child, 'click', function (e) {console.log (' child');}); addEvent (parent, 'click', function (e) {console.log (' parent');}); addEvent (grandparent, 'click', function (e) {console.log (' grandparent');}); addEvent (document, 'click', function (e) {console.log (' document');}) AddEvent ('html',' click', function (e) {console.log ('html');}) addEvent (window,' click', function (e) {console.log ('window');})})

The addEventListener method has a third optional parameter, useCapture, whose default value is false, and the event will occur during the bubbling phase or, if true, during the capture phase. If you click the child element, it will print child,parent,grandparent,html,document and window on the console, respectively, which is the event bubbling.

The above is all the content of the article "example Analysis of event Bubble in JavaScript". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Events elements stages examples analysis content grandparents articles three code values interests parameters guys buddies that is methods more knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Redmi macOS Shulou Information NVidia