Table of Contents
2. Bubble mechanism
Home Web Front-end JS Tutorial Understand 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
javascript Event 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>
Copy after login

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>
Copy after login
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>

Copy after login

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>
Copy after login

预期上述代码会单击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>
Copy after login

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

方法二:事件包含最初触发事件的节点引用 和 当前处理事件节点的引用,那如果节点只处理自己触发的事件即可,不是自己产生的事件不处理。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>
Copy after login

比较:

从事件传递上看:

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

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

优缺点:

  • 方法一缺点:为了实现点击特定的元素显示对应的信息,方法一要求每个元素的子元素也必须终止事件的冒泡传递,即跟别的元素功能上强关联,这样的方法会很脆弱。比如,如果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>
Copy after login

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

                                                                                                          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 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 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)

Understand the event bubbling mechanism: Why does a click on a child element affect the event of the parent element? Understand the event bubbling mechanism: Why does a click on a child element affect the event of the parent element? Jan 13, 2024 pm 02:55 PM

Understanding event bubbling: Why does a click on a child element trigger an event on the parent element? Event bubbling means that in a nested element structure, when a child element triggers an event, the event will be passed to the parent element layer by layer like bubbling, until the outermost parent element. This mechanism allows events on child elements to be propagated throughout the element tree and trigger all related elements in turn. To better understand event bubbling, let's look at a specific example code. HTML code: <divid="parent&q

Why does event bubbling trigger twice? Why does event bubbling trigger twice? Feb 22, 2024 am 09:06 AM

Why does event bubbling trigger twice? Event bubbling (Event Bubbling) means that in the DOM, when an element triggers an event (such as a click event), the event will bubble up from the element to the parent element until it bubbles to the top-level document object. . Event bubbling is part of the DOM event model, which allows developers to bind event listeners to parent elements, so that when child elements trigger events, the events can be captured and processed through the bubbling mechanism. However, sometimes developers encounter events that bubble up and trigger twice.

Reasons and solutions for jQuery .val() failure Reasons and solutions for jQuery .val() failure Feb 20, 2024 am 09:06 AM

Title: Reasons and solutions for the failure of jQuery.val() In front-end development, jQuery is often used to operate DOM elements. The .val() method is widely used to obtain and set the value of form elements. However, sometimes we encounter situations where the .val() method fails, resulting in the inability to correctly obtain or set the value of the form element. This article will explore the causes of .val() failure, provide corresponding solutions, and attach specific code examples. 1.Cause analysis.val() method

Why can't click events in js be executed repeatedly? Why can't click events in js be executed repeatedly? May 07, 2024 pm 06:36 PM

Click events in JavaScript cannot be executed repeatedly because of the event bubbling mechanism. To solve this problem, you can take the following measures: Use event capture: Specify an event listener to fire before the event bubbles up. Handing over events: Use event.stopPropagation() to stop event bubbling. Use a timer: trigger the event listener again after some time.

What scenarios can event modifiers in vue be used for? What scenarios can event modifiers in vue be used for? May 09, 2024 pm 02:33 PM

Vue.js event modifiers are used to add specific behaviors, including: preventing default behavior (.prevent) stopping event bubbling (.stop) one-time event (.once) capturing event (.capture) passive event listening (.passive) Adaptive modifier (.self)Key modifier (.key)

Why does the event bubbling mechanism trigger twice? Why does the event bubbling mechanism trigger twice? Feb 25, 2024 am 09:24 AM

Why does event bubbling happen twice in a row? Event bubbling is an important concept in web development. It means that when an event is triggered in a nested HTML element, the event will bubble up from the innermost element to the outermost element. This process can sometimes cause confusion. One common problem is that event bubbling occurs twice in a row. In order to better understand why event bubbling occurs twice in a row, let's first look at a code example:

Which JS events don't bubble up? Which JS events don't bubble up? Feb 19, 2024 pm 09:56 PM

What are the situations in JS events that will not bubble up? Event bubbling (Event Bubbling) means that after an event is triggered on an element, the event will be transmitted upward along the DOM tree starting from the innermost element to the outermost element. This method of transmission is called event bubbling. However, not all events can bubble up. There are some special cases where events will not bubble up. This article will introduce the situations in JavaScript where events will not bubble up. 1. Use stopPropagati

What is event bubbling? In-depth analysis of event bubbling mechanism What is event bubbling? In-depth analysis of event bubbling mechanism Feb 20, 2024 pm 05:27 PM

What is event bubbling? In-depth analysis of the event bubbling mechanism Event bubbling is an important concept in web development, which defines the way events are delivered on the page. When an event on an element is triggered, the event will be transmitted starting from the innermost element and passed outwards until it is passed to the outermost element. This delivery method is like bubbles bubbling in water, so it is called event bubbling. In this article, we will analyze the event bubbling mechanism in depth. The principle of event bubbling can be understood through a simple example. Suppose we have an H

See all articles