Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of event capture in JavaScript

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

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

What is event capture?

When an event occurs on a DOM element, the event does not happen exactly on that element. In the capture phase, the event starts at window and goes all the way to the element that triggers the event. Window---- > document---- > html---- > body-> Target element

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 window,document,html,grandparent and parent on the console, respectively, which is called event capture.

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report