


Detailed introduction to Javascript event bubbling mechanism (graphic tutorial)
This article mainly introduces relevant information about the detailed introduction of Javascript event bubbling mechanism. Friends who need it can refer to
1. Events
in the browser Client application platforms are basically event-driven, that is, when an event occurs, corresponding actions are taken.
Browser events represent signals that something has happened. The explanation of the event is not the focus of this article. Friends who have not yet understood it can visit the W3school tutorial to learn more. This will help to better understand the following content.
2. Bubble mechanism
What is bubbling?
The following picture should be fulfilled. The bubbles start from the bottom of the water, from deep to shallow, rising to the top. On the way up, the bubbles pass through different depth levels of water.
Correspondingly: This bubble is equivalent to our event here, and the water is equivalent to our entire dom tree; events start from the bottom layer of the dom tree The layer is passed up until it is passed to the root node of the dom.
Simple case analysis
The following is a simple example to illustrate the principle of bubbling:
Define an html, which contains three Simple dom elements: p1, p2, span, p2 contains span, p1 contains p2; and they are all under body:
<body id="body"> <p id="box1" class="box1"> <p id="box2" class="box2"> <span id="span">This is a span.</span> </p> </p> </body>
The interface prototype is as follows:
## On this basis, we implement the following functions:
<script type="text/javascript"> 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", p2, p1, and body in sequence, the following information is output:
Analyze the above results:
Generally, there will be some information during the event delivery process, which are the components of the event:The time when the event occurred The location where the event occurred The type of the event The current handler of the event Other information,
##
The complete html code is as follows:
Insert title here <script type="text/javascript"> 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> <body id="body"> <p id="box1" class="box1"> <p id="box2" class="box2"> <span id="span">This is a span.</span> </p> </p> </body>
b. Terminate event bubbling
We now want to implement such a function. When p1 is clicked, "Hello, I am the outermost p" will pop up. ", when you click p2, "Hello, I am the second layer p" pops up; when you click span, "Hello, I am span." pops up. From this we will have the following javascript fragment:
<script type="text/javascript"> window.onload = function() { document.getElementById("box1").addEventListener("click",function(event){ alert("您好,我是最外层p。"); }); document.getElementById("box2").addEventListener("click",function(event){ alert("您好,我是第二层p。"); }); document.getElementById("span").addEventListener("click",function(event){ alert("您好,我是span。"); }); } </script>
It is expected that when the above code clicks span, a pop-up box will appear "Hello, I am span." Yes, It does pop up such a dialog box:
## This can not only produce this dialog box. After clicking OK, the following dialog box will pop up in turn:
这显然不是我们想要的! 我们希望的是点谁显示谁的信息而已。为什么会出现上述的情况呢? 原因就在于事件的冒泡,点击span的时候,span 会把产生的事件往上冒泡,作为父节点的p2 和 祖父节点的p1也会收到此事件,于是会做出事件响应,执行响应函数。现在问题是发现了,但是怎么解决呢?
方法一:我们来考虑一个形象一点的情况:水中的一个气泡正在从底部往上冒,而你现在在水中,不想让这个气泡往上冒,怎么办呢?——把它扎破!没了气泡,自然不会往上冒了。类似地,对某一个节点而言,如果不想它现在处理的事件继续往上冒泡的话,我们可以终止冒泡:
在相应的处理函数内,加入 event.stopPropagation() ,终止事件的广播分发,这样事件停留在本节点,不会再往外传播了。修改上述的script片段:
<script type="text/javascript"> window.onload = function() { document.getElementById("box1").addEventListener("click",function(event){ alert("您好,我是最外层p。"); event.stopPropagation(); }); document.getElementById("box2").addEventListener("click",function(event){ alert("您好,我是第二层p。"); 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元素,这时判断两者相等,则执行相应的处理函数。而事件传递给 p2 的时候,event.currentTarget变成 p2,这时候判断二者不相等,即事件不是p2 本身产生的,就不作响应处理逻辑。
<script type="text/javascript"> window.onload = function() { document.getElementById("box1").addEventListener("click",function(event){ if(event.target == event.currentTarget) { alert("您好,我是最外层p。"); } }); document.getElementById("box2").addEventListener("click",function(event){ if(event.target == event.currentTarget) { alert("您好,我是第二层p。"); } }); 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 type="text/javascript"> 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 "p1": alert("您好,我是第二层p。"); break; case "p2": alert("您好,我是最外层p。"); break; } } </script>
结果会是点击不同的元素,只弹出相符合的提示,不会有多余的提示。
Through the above method, we have handed over the processing functions that each element should have to its grandparent node body element to complete. In other words, span, p2, and p1 will have their own response logic. Delegate it to the body and let it complete the corresponding logic without implementing the corresponding logic yourself. This mode is the so-called event delegation.
The following is a schematic diagram:
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Detailed explanation of JavaScript cookie and simple example application (picture and text tutorial)
Native and powerful DOM selection Detailed introduction to querySelector (code attached)
javascript Several methods of commenting code (graphic tutorial)
The above is the detailed content of Detailed introduction to Javascript event bubbling mechanism (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

Notepad++7.3.1
Easy-to-use and free code editor
