search
HomeWeb Front-endJS TutorialUnderstand the event bubbling mechanism in JS in one article

Understand the event bubbling mechanism in JS in one article

Aug 04, 2022 pm 08:37 PM
javascriptEvent bubbling

This article talks about event bubbling and gives you an in-depth understanding of the event bubbling mechanism in JS. I hope it will be helpful to you!

Understand the event bubbling mechanism in JS in one article

1. Event

In the browser client application platform, it is basically generated It is event-driven, that is, an event occurs, and then corresponding actions are taken.

Browser events represent signals that something has happened. The explanation of the incident is not the focus of this article. Friends who have not yet understood it can learn more on Baidu, which will help to better understand the following content.

2. Bubble mechanism

#What is bubbling?

You should understand the picture below. The bubbles start from the bottom of the water and rise up, from deep to shallow, to the top. On the way up, the bubbles pass through different depth levels of water.

                                                                                                                                                                 The entire DOM tree; events are passed up from the bottom layers of the DOM tree until they are passed to the root node of the DOM. Understand the event bubbling mechanism in JS in one article

Simple case analysis

The following is a simple example to illustrate the bubbling principle:

Definition An HTML, there are three simple DOM elements: div1, div2, span, div2 contains span, div1 contains div2; and they are all under the body:

	<div>
		<div>
			<span>This is a span.</span>
		</div>
	</div>

Interface prototype As follows:

                                                                                                                               , when the body captures the event event, print out the time when the event occurred and the node information that triggered the event:

<script>
	window.onload = function() {
		document.getElementById("body").addEventListener("click",eventHandler);
	}
	function eventHandler(event) {
		console.log("时间:"+new Date(event.timeStamp)+" 产生事件的节点:" + event.target.id +"  当前节点:"+event.currentTarget.id);
	}
</script>
When we click "This is span", div2, div1, and body in sequence, the output The following information:

                                                                                                                                                                                                                               Understand the event bubbling mechanism in JS in one article

Analysis of the above results: , or the sub-element div2 of div, and span. When these elements are clicked, a click event will be generated, and the body will capture it, and then call the corresponding event processing function. Just as bubbles in water rise from the bottom up, so do events.

The schematic diagram of event delivery is as follows:

# Generally, there will be some information during the event delivery process. These are Components of an event: Time when the event occurred Where the event occurred Type of event Current handler of the event Other information Understand the event bubbling mechanism in JS in one article,

The complete html code is as follows:

nbsp;html>



<script></script>
Insert title here

 
<script>
	window.onload = function() {
		document.getElementById("body").addEventListener("click",eventHandler);
	}
	function eventHandler(event) {
		console.log("时间:"+new Date(event.timeStamp)+" 产生事件的节点:" + event.target.id +"  当前节点:"+event.currentTarget.id);
	}
</script>
 


	<div>
		<div>
			<span>This is a span.</span>
		</div>
	</div>

Understand the event bubbling mechanism in JS in one articleb. Bubbling of termination event

We now want to implement such a function, When div1 is clicked, "Hello, I am the outermost div." pops up. When div2 is clicked, "Hello, I am the second layer div" pops up; when span is clicked, "Hello, I am the second div" pops up. span." From this we will have the following javascript fragment:

<script>
	window.onload = function() {
		document.getElementById("box1").addEventListener("click",function(event){
			alert("您好,我是最外层div。");
		});
		document.getElementById("box2").addEventListener("click",function(event){
			alert("您好,我是第二层div。");
		});
		document.getElementById("span").addEventListener("click",function(event){
			alert("您好,我是span。");
		});
	}
</script>

预期上述代码会单击span 的时候,会出来一个弹出框 "您好,我是span。" 是的,确实弹出了这样的对话框:

Understand the event bubbling mechanism in JS in one article

然而,不仅仅会产生这个对话框,当点击确定后,会依次弹出下列对话框:

Understand the event bubbling mechanism in JS in one article     Understand the event bubbling mechanism in JS in one article

这显然不是我们想要的! 我们希望的是点谁显示谁的信息而已。为什么会出现上述的情况呢? 原因就在于事件的冒泡,点击span的时候,span 会把产生的事件往上冒泡,作为父节点的div2 和 祖父节点的div1也会收到此事件,于是会做出事件响应,执行响应函数。现在问题是发现了,但是怎么解决呢?

方法一:我们来考虑一个形象一点的情况:水中的一个气泡正在从底部往上冒,而你现在在水中,不想让这个气泡往上冒,怎么办呢?——把它扎破!没了气泡,自然不会往上冒了。类似地,对某一个节点而言,如果不想它现在处理的事件继续往上冒泡的话,我们可以终止冒泡:

在相应的处理函数内,加入  event.stopPropagation()   ,终止事件的广播分发,这样事件停留在本节点,不会再往外传播了。修改上述的script片段:

<script>
	window.onload = function() {
		document.getElementById("box1").addEventListener("click",function(event){
			alert("您好,我是最外层div。");
			event.stopPropagation();
		});
		document.getElementById("box2").addEventListener("click",function(event){
			alert("您好,我是第二层div。");
			event.stopPropagation();
		});
		document.getElementById("span").addEventListener("click",function(event){
			alert("您好,我是span。");
			event.stopPropagation();
		});
	}
</script>

经过这样一段代码,点击不同元素会有不同的提示,不会出现弹出多个框的情况了。

方法二:事件包含最初触发事件的节点引用 和 当前处理事件节点的引用,那如果节点只处理自己触发的事件即可,不是自己产生的事件不处理。event.target 引用了产生此event对象的dom 节点,而event.currrentTarget 则引用了当前处理节点,我们可以通过这 两个target 是否相等。

            比如span 点击事件,产生一个event 事件对象,event.target 指向了span元素,span处理此事件时,event.currentTarget 指向的也是span元素,这时判断两者相等,则执行相应的处理函数。而事件传递给 div2 的时候,event.currentTarget变成 div2,这时候判断二者不相等,即事件不是div2 本身产生的,就不作响应处理逻辑。               

<script>
	window.onload = function() {
		document.getElementById("box1").addEventListener("click",function(event){
			if(event.target == event.currentTarget)
			{
			    alert("您好,我是最外层div。");
			}
		});
		document.getElementById("box2").addEventListener("click",function(event){
			if(event.target == event.currentTarget)
			{
				alert("您好,我是第二层div。");
			}
		});
		document.getElementById("span").addEventListener("click",function(event){
			if(event.target == event.currentTarget)
			{
			    alert("您好,我是span。");
				
			}
		});
	}
</script>

比较:

从事件传递上看:

  • 方法一在于取消事件冒泡,即当某些节点取消冒泡后,事件不会再传递;

  • 方法二在于不阻止冒泡,过滤需要处理的事件,事件处理后还会继续传递;

优缺点:

  • 方法一缺点:为了实现点击特定的元素显示对应的信息,方法一要求每个元素的子元素也必须终止事件的冒泡传递,即跟别的元素功能上强关联,这样的方法会很脆弱。比如,如果span 元素的处理函数没有执行冒泡终止,则事件会传到p2 上,这样会造成p2 的提示信息;

  • 方法二缺点:方法二为每一个元素都增加了事件监听处理函数,事件的处理逻辑都很相似,即都有判断 if(event.target == event.currentTarget),这样存在了很大的代码冗余,现在是三个元素还好,当有10几个,上百个又该怎么办呢?

还有就是为每一个元素都有处理函数,在一定程度上增加逻辑和代码的复杂度。

        我们再来分析一下方法二:方法二的原理是 元素收到事件后,判断事件是否符合要求,然后做相应的处理,然后事件继续冒泡往上传递;

既然事件是冒泡传递的,那可不可以让某个父节点统一处理事件,通过判断事件的发生地(即事件产生的节点),然后做出相应的处理呢?答案是可以的,下面通过给body 元素添加事件监听,然后通过判断event.target 然后对不同的target产生不同的行为。

        将方法二的代码重构一下:

<script>
	window.onload = function() {
		document.getElementById("body").addEventListener("click",eventPerformed);
	}
	function eventPerformed(event) {
		var target = event.target;
		switch (target.id) {
		case "span": 
			alert("您好,我是span。");
			break;
		case "div1":
			alert("您好,我是第二层div。");
			break;
		case "div2":
			alert("您好,我是最外层div。");
			break;
		}
	}
</script>

结果会是点击不同的元素,只弹出相符合的提示,不会有多余的提示。

                                                                                                          p1 delegates its response logic to the body and lets it complete the corresponding logic. It does not implement the corresponding logic. This mode is the so-called event delegation.
The following is a schematic diagram:


Understand the event bubbling mechanism in JS in one article[Related recommendations:

javascript learning Tutorial

The above is the detailed content of Understand the event bubbling mechanism in JS in one article. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor