Home Web Front-end JS Tutorial JS bubbling event parsing guide: must-read material for beginners

JS bubbling event parsing guide: must-read material for beginners

Jan 13, 2024 am 10:21 AM
beginner js bubbling event Application scenario analysis

JS bubbling event parsing guide: must-read material for beginners

Must-read for beginners: Introduction to JS bubbling events and analysis of application scenarios

Introduction:
In Web development, JavaScript (JS) is a very important programming language. After mastering the basic syntax and operations of JS, understanding the event mechanism of JS is the key to further improving your capabilities. Among them, bubbling events are an important concept in the JS event mechanism. This article will introduce the concepts, principles and practical application scenarios of JS bubbling events in detail, and provide specific code examples to help beginners better understand and master them.

1. Concept:
Bubbling event means that when an element triggers an event, the event will be triggered in the parent element in sequence until it is triggered to the outermost ancestor element. This process is like a bubble rising from the bottom, so it is called a bubbling event.

2. Principle:
The principle of bubbling events is based on the DOM tree structure, that is, the document object model. In a web page, all elements (including HTML tags and elements created by JS) can be regarded as nodes of a DOM tree. When an event occurs on an element, the JS engine will trigger the same type of event in sequence according to the structure of the DOM tree, that is, trigger the same event on the parent element until the outermost ancestor element.

3. Code example 1: Basic use of bubbling events
The following is a simple HTML code fragment that demonstrates the basic use of bubbling events:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

<!DOCTYPE html>

<html>

<head>

  <title>冒泡事件示例</title>

</head>

<body>

  <div id="outer">

    <div id="inner">

      <button id="btn">点击触发冒泡事件</button>

    </div>

  </div>

 

  <script>

    // 选择DOM元素

    const outer = document.querySelector('#outer');

    const inner = document.querySelector('#inner');

    const btn = document.querySelector('#btn');

 

    // 添加冒泡事件监听

    outer.addEventListener('click', function() {

      console.log('父级元素outer被点击');

    });

 

    inner.addEventListener('click', function() {

      console.log('子级元素inner被点击');

    });

 

    btn.addEventListener('click', function() {

      console.log('按钮被点击');

    });

  </script>

</body>

</html>

Copy after login

In the above code, We added click event listeners to the parent element outer, the child element inner and the button element btn. When we click the button, the following information will be output on the console:

1

2

3

按钮被点击

子级元素inner被点击

父级元素outer被点击

Copy after login

This is because the click event of the button element bubbles to the inner child element and the parent element outer, and triggers the corresponding event callback function.

4. Code example 2: Application scenarios of bubbling events
The application scenarios of bubbling events are very wide. Below we take the shopping cart item deletion function as an example to demonstrate the practical application of bubbling events.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

<!DOCTYPE html>

<html>

<head>

  <title>冒泡事件应用场景示例</title>

  <style>

    .item {

      margin-bottom: 10px;

      padding: 5px;

      border: 1px solid #ccc;

    }

    .delete-btn {

      float: right;

      cursor: pointer;

    }

  </style>

</head>

<body>

  <div id="cart">

    <div class="item">

      商品1

      <span class="delete-btn">删除</span>

    </div>

    <div class="item">

      商品2

      <span class="delete-btn">删除</span>

    </div>

    <div class="item">

      商品3

      <span class="delete-btn">删除</span>

    </div>

  </div>

 

  <script>

    // 选择DOM元素

    const cart = document.querySelector('#cart');

 

    // 添加冒泡事件监听

    cart.addEventListener('click', function(event) {

      const target = event.target;

      if (target.classList.contains('delete-btn')) {

        const item = target.parentNode;

        item.remove();

        console.log('删除成功');

      }

    });

  </script>

</body>

</html>

Copy after login

In the above code, we added a click event listener for the delete button of each product element. When the delete button is clicked, the "Delete Successfully" message is output in the console and the corresponding product element is removed from the shopping cart. This is because when the delete button is clicked, the bubbling event will trigger the click event listening function on the parent element cart. By determining whether the clicked target element is a delete button, the specific deletion function can be implemented.

Summary:
Bubble events are an important concept in the JS event mechanism and a part that cannot be ignored in Web development. Through this article's detailed introduction to the concepts, principles, and practical application scenarios of bubbling events, I believe that beginners have already had a preliminary understanding and mastery of bubbling events. I hope this article can help beginners better understand and apply bubbling events and improve their JS programming skills.

The above is the detailed content of JS bubbling event parsing guide: must-read material for beginners. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Become a C expert: Five must-have compilers recommended Become a C expert: Five must-have compilers recommended Feb 19, 2024 pm 01:03 PM

From Beginner to Expert: Five Essential C Compiler Recommendations With the development of computer science, more and more people are interested in programming languages. As a high-level language widely used in system-level programming, C language has always been loved by programmers. In order to write efficient and stable code, it is important to choose a C language compiler that suits you. This article will introduce five essential C language compilers for beginners and experts to choose from. GCCGCC, the GNU compiler collection, is one of the most commonly used C language compilers

WooCommerce Tax Guide: A Guide for Beginners WooCommerce Tax Guide: A Guide for Beginners Sep 04, 2023 am 08:25 AM

Now that we have learned about WooCommerce products and their related settings, let’s take a look at WooCommerce tax configuration options. Tax Setup As an online store owner, you never want to mess with tax rules and issues. WooCommerce helps you with this, offering multiple options to address all tax settings, which may vary depending on your country and individual store requirements. These options can be found at: WooCommerce->Settings->Taxes. Once you enter the Tax Settings tab, you will see a main Tax Settings section with three different tax brackets. These are: Tax Options Standard Rates Reduced Interest Rates Zero Interest Rates Taxes

C++ or Python, which one is more suitable for beginners? C++ or Python, which one is more suitable for beginners? Mar 25, 2024 am 10:54 AM

C++ or Python, which one is more suitable for beginners? In this era of information technology sweeping the world, programming ability has become an essential skill. In the process of learning programming, choosing a suitable programming language is particularly important. Among many programming languages, C++ and Python are two popular choices for beginners. So, which one is more suitable for beginners, C++ or Python? The following will compare the advantages and disadvantages of the two in various aspects, and why choosing a certain language is more helpful for beginners to get started with programming.

Python beginners must learn: Master the basic usage of lambda functions Python beginners must learn: Master the basic usage of lambda functions Feb 02, 2024 pm 06:41 PM

Essential for beginners: To master the basic usage of lambda functions in Python, specific code examples are required. Overview: Python is a simple and easy-to-learn programming language. It has attracted the love of many programmers with its concise and flexible syntax. In Python, a lambda function is a special anonymous function that can be defined directly where the function is required without giving it a name. This article will introduce the basic use of lambda functions and provide specific code examples to help beginners better understand

Pandas Beginner's Guide: HTML Table Data Reading Tips Pandas Beginner's Guide: HTML Table Data Reading Tips Jan 09, 2024 am 08:10 AM

Beginner's Guide: How to Read HTML Tabular Data with Pandas Introduction: Pandas is a powerful Python library for data processing and analysis. It provides flexible data structures and data analysis tools, making data processing simpler and more efficient. Pandas can not only process data in CSV, Excel and other formats, but can also directly read HTML table data. This article will introduce how to use the Pandas library to read HTML table data, and provide specific code examples to help beginners

Should programming beginners learn C language or C first? Should programming beginners learn C language or C first? Mar 18, 2024 pm 03:15 PM

Title: Should programming beginners learn C language or C first? In the field of programming, C language and C are two very important programming languages, both of which have their own unique characteristics and advantages. For beginners, choosing which language to learn can be a bit confusing. This article will discuss this issue and give some specific code examples to help beginners better understand the differences between the two languages. First, let's take a look at the C language. C language is a powerful and widely used programming language. It is developed from assembly language.

A must-read for beginners: How to choose the appropriate Django version according to your needs? A must-read for beginners: How to choose the appropriate Django version according to your needs? Jan 19, 2024 am 08:20 AM

For beginners, choosing the appropriate Django version is an important and must-face issue. As an efficient web framework, Django has a large number of users and developers, so it also has multiple versions to meet the needs of different products and applications. But how do you choose the right Django version based on your project needs? Below we will use some examples to help you choose the version that suits you. Confirm that the database used Django supports multiple databases, including MySQL, Postgre

A beginner's guide to making scatter plots with matplotlib A beginner's guide to making scatter plots with matplotlib Jan 17, 2024 am 09:58 AM

matplotlib is one of the most commonly used data visualization libraries in Python. It offers a variety of plotting options, including line graphs, bar graphs, scatter plots, and more. This article will teach you how to use matplotlib to draw scatter plots, and provide specific code examples to help beginners get started quickly. 1. Import the matplotlib module. Before you start using matplotlib to draw scatter plots, first, you need to import the relevant Python modules. The code is as follows: importpa

See all articles