Table of Contents
Bubble event
Features:
Two methods to prevent bubbling events
cancelBubble
stopPropagation()
Using this method, multiple identical event response functions can be bound to the same element.
事件的传播
Home Web Front-end JS Tutorial Briefly understand the bubbling, delegation, binding and propagation of JavaScript events

Briefly understand the bubbling, delegation, binding and propagation of JavaScript events

Jul 13, 2022 pm 12:07 PM
javascript

This article brings you relevant knowledge about javascript, which mainly organizes issues related to bubbling, delegation, binding and propagation of JavaScript events, including bubbling events, delegation Events, binding events through addEventListener(), etc. Let’s take a look at them together. I hope it will be helpful to everyone.

Briefly understand the bubbling, delegation, binding and propagation of JavaScript events

[Related recommendations: javascript video tutorial, web front-end

Bubble event

  1. Event bubbling means that the event is initially received by the most specific element, and then propagates upward to less specific nodes.
  2. Event bubbling is enabled by default, but event bubbling can be controlled through js code.

Features:

  • When our event function is triggered, the event function will actually receive an event object.

  • When we execute the event.stopPropagation() method in our event function, the event bubbling ends here.

  • Not all types of events support event bubbling.

  • Event bubbling will only trigger event functions of the same type.

Two methods to prevent bubbling events

There are two methods to prevent bubbling events, one of which is an attribute and the other is a method.

cancelBubble

Set or return whether the event should be propagated to the upper level.

Syntax: event.cancelBubble = true;

stopPropagation()

Prevent events from propagating further in the event stream.

Syntax: event.stopPropagation();

Example: Bind click response functions to three objects that are mutually parent and child.

Briefly understand the bubbling, delegation, binding and propagation of JavaScript events

window.onload = function(){
      var span = document.getElementById("sp");
      span.onclick = function(){
          alert('span标签');
          
      }
      var box = document.getElementById('box3');
      box3.onclick = function(){
          alert('box3');
      }
      var body = document.body;
      body.onclick = function(){
          alert('body');
      }}
Copy after login

Prevent bubbling of the box:
Briefly understand the bubbling, delegation, binding and propagation of JavaScript events##

window.onload = function(){
      var span = document.getElementById("sp");
      span.onclick = function(){
          alert('span标签');
          
      }
      var box = document.getElementById('box3');
      box3.onclick = function(event){
          alert('box3');
           event.stopPropagation();

      }
      var body = document.body;
      body.onclick = function(){
          alert('body');
      }}
Copy after login
Delegated event

When we have a bunch of sub-tags For the same event, you can add events to it by traversing subtags, but if a new subtag element is added, you must rebind the new subtag element, otherwise it will be invalid.

Features

Bind the event to the

ancestor element, so that when the event on the child element is triggered, it will bubble up to the ancestor element , thereby handling the event through the ancestor element's response event. Using bubbling and delegation, you can reduce the number of event bindings and improve program performance.

Get the clicked element

When we bind an event to the ancestor element, no matter which element we click on the ancestor element, the corresponding event will be triggered. We only hope that when we When an event is triggered only by clicking on an element within the ancestor element, a judgment condition needs to be given to determine whether it is the element we want to trigger the event.

target

Returns the element that triggered the event.

Syntax:

event.taget;

##

window.onload = function(){
     var ul = document.getElementById('ul1');
     ul.onclick = function(event){
         if(event.target.className == 'abq'){
             alert('事件触发!!')
         } 
     }
     //添加超链接
     document.getElementById('bt1').onclick = function(){
         var li = document.createElement('li');
         li.innerHTML = "<a>新建的标签</a>";
         ul.appendChild(li);
     }
 }
Copy after login
Briefly understand the bubbling, delegation, binding and propagation of JavaScript eventsBind events through addEventListener()

Using this method, multiple identical event response functions can be bound to the same element.

Parameters:
The string of the event, do not use the on
  1. callback function, which will be called when the event is triggered
  2. Whether to trigger the event in the capture phase requires a Boolean value, the default is false
  3. Use addEventListener() to bind multiple response functions to the same event of an element at the same time, so that when When an event is triggered, the response function will be executed in the order in which the function is bound!

window.onload = function(){
    var bt = document.getElementById('bt1');
    bt.addEventListener('click',function(){
        alert('触发的第一个单击相应函数!')
    },false);
    bt.addEventListener('click',function(){
        alert('触发的第二个单击相应函数!')
    },false);
    bt.addEventListener('click',function(){
        alert('触发的第三个单击相应函数!')
    },false);}
Copy after login

事件的传播

  • 关于事件的传播网景公司和微软公司有不同的理解:
    微软公司认为事件应该是由内向外传播,也就是当事件触发时,应该先触发当前元素上的事件,然后再向当前元素的祖先元素上传播,也就说事件应该在冒泡阶段执行
    网景公司认为事件应该是由外向内传播的,也就是当前事件触发时,应该先触发当前元素的最外层的祖先元素的事件,然后在向内传播给后代元素。
  • W3C综合了两个公司的方案,将事件传播分成了三个阶段:
  1. 捕获阶段
    在捕获阶段时从最外层的祖先元素,向目标元素进行事件的捕获,但是默认此时不会触发事件。
  2. 目标阶段
    事件捕获到目标元素,捕获结束开始在目标元素上触发事件。
  3. 冒泡阶段
    事件从目标元素向他的祖先元素传递,依次触发祖先元素上的事件。

Briefly understand the bubbling, delegation, binding and propagation of JavaScript events

在冒泡阶段执行响应函数。默认第三个参数为false

window.onload = function(){
     var box1 = document.getElementById('box1');
     var box2 = document.getElementById('box2');
     var box3 = document.getElementById('box3');
     box1.addEventListener('click',function(){
         alert('box1');
     },false);
     box2.addEventListener('click',function(){
         alert('box2');
     },false);
     box3.addEventListener('click',function(){
         alert('box3');
     },false);
 }
Copy after login

Briefly understand the bubbling, delegation, binding and propagation of JavaScript events

如果希望在捕获阶段就触发事件,可以将addEventListener()的第三个参数设置为true!
Briefly understand the bubbling, delegation, binding and propagation of JavaScript events

window.onload = function(){
     var box1 = document.getElementById('box1');
     var box2 = document.getElementById('box2');
     var box3 = document.getElementById('box3');
     box1.addEventListener('click',function(){
         alert('box1');
     },true);
     box2.addEventListener('click',function(){
         alert('box2');
     },true);
     box3.addEventListener('click',function(){
         alert('box3');
     },true);
 }
Copy after login

【相关推荐:javascript视频教程web前端

The above is the detailed content of Briefly understand the bubbling, delegation, binding and propagation of JavaScript events. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles