Learn more about event bubbling and capturing in JavaScript
This article will take you through event bubbling and capturing, and let you understand the js event target search method (bubbling and capturing), event proxy, the difference between e.target and e.currentTarget, preventing bubbling and capturing, Cancel the default event, hope it helps everyone!
1. EventTarget event target search method (bubble and capture)
Event target refers to the element to which the event is bound, elemet .addEventListener('click',function(){}) The elemet here is the event target.
Bubbling and capturing:
-
Bubble events:
- The event defaults to bubbling execution from bottom to top. Taking click events as an example, when we click on a child element, click events on the parent element and above can also be triggered. The order of event execution is from bottom to top, which is the bubbling event.
-
Capture events:
- Of course, there is also a top-down capture method. Still taking the click event as an example, when a child element is bound to a click event, and we click on the child element, the click events bound to the parent element and above elements will also be executed. The execution order of events is from top to bottom, which is the capture event.
##addEventListener(type,listener,useCapture) Simple analysis:
- type: event Type
- listener: event listening processing function
- useCapture: set the event search method
- false, bubbling event (default value)
- true, capture event
Parameter useCapture analysis:
Key point! ! The entire process of triggering an event target is divided into two stages (capturing and bubbling). useCapture This value determines at which stage the triggering of the event target is executed.
Sequence analysis of bubbling and capturing:
- It can be seen from the picture It can be seen that the event is captured first and then the event is bubbled. Event capture is from top to bottom (external events are triggered first), and event bubbling is from bottom to top (internal events are triggered first).
- The process of capturing is from unspecific to specific, and bubbling is from specific to unspecific.
- Although
- capture takes precedence
, bubbling events are the default method of delivery. This means that events are triggered in the bubbling stage by default.
Point! ! The search for event targets is divided into two stages: "bubble" and "capture". The order in which event targets are triggered depends on which stage. If there are both captures and bubbles in the nested elements, the capture must take priority. After the events in the capture phase are executed, the events in the bubbling phase will be executed.
Code demonstration:
<div> 这是div1 <div> 这是div2 <div>这是div3</div> </div> </div> <script> let div1 = document.getElementById('div1'); let div2 = document.getElementById('div2'); let div3 = document.getElementById('div3'); div1.addEventListener('click',function(){ console.log("这是div1的点击事件"); },false); div2.addEventListener('click',function(){ console.log("这是div2的点击事件"); },false); div3.addEventListener('click',function(){ console.log("这是div3的点击事件"); },false); </script>When we click on div3, as can be seen from the console results below, the events here are Executed during the bubbling phase.
div1.addEventListener to true. As shown below, div1 is executed first, indicating the capture stage. Prioritizes the bubbling phase.
Bubbles and
Capture.
Use event bubbling to complete the event proxy mechanism:
- 列表1
- 列表2
li in the above list. Click to obtain the content in li. Generally, we use for to traverse the elements to bind the click event.
let lis = document.querySelectorAll('li'); for (let i = 0; i If we have 10,000 <p>li<code> nodes, we need to bind 10,000 events using the above method, which greatly affects the code performance. So we can use the bubbling mechanism to solve the above problem, which is to bind the event to the parent element </code>ul<code>. Look at the following code: </code></p><pre class="brush:php;toolbar:false">
- 列表1
- 列表2
Event object (e): Whether it is addEventListener binding event or direct ".event name", the first parameter in the event listening processing function is event Object. The event object contains detailed information about the event. For example, this object contains:
Event source, event id, event type, event-bound element, clicked position when the event is triggered, etc. Among them, e.target can access the event source, which is the source of triggering this event.
既然能给父元素绑定事件监听,又能拿到触发的源头。所以我们通过“e.target”+“冒泡机制”就可以减少事件的绑定,能提升不少的性能。
依次点击列表1与列表2:
总结:通过上面代码我们知道了“事件对象”+“冒泡机制”可以实现事件委托。事件委托就是当事件触发时,通过事件冒泡(或事件捕获)把要做的事委托给父元素来处理。
三、e.target与e.currentTarget的区别:
- e.target 指向的是触发事件监听的对象(事件源)。
- e.currentTarget 指向添加监听事件的对象(绑定事件的dom元素)。
四、阻止冒泡与捕获
为什么要阻止冒泡或捕获?
点击当前元素时以冒泡的方式传递事件如果上级元素绑定了同样的事件,就会因为冒泡传递导致触发。同样捕获的过程中,也会触发与当前元素绑定的相同事件的上级。只是触发顺序不同。
事件代理一般使用的冒泡,当然阻止冒泡一般不会影响事件代理,因为顺序问题只会影响捕获事件,这也是为什么都使用冒泡实现事件代理机制。
阻止冒泡或捕获的方法
这里我不考虑兼容性问题,我相信不久将来兼容性可以得到解决。
阻止冒泡w3c推介的方法是event.stopPropagation(),顾名思义停止传播,他是事件对象(event)的方法,此方法是阻止目标元素的继续冒泡(或捕获)
。
event.stopPropagation()阻止冒泡:
<div> 这是div1 <div> 这是div2 <div>这是div3</div> </div> </div> <script> let div1 = document.getElementById('div1'); let div2 = document.getElementById('div2'); let div3 = document.getElementById('div3'); div1.onclick = function (e) { alert('div1'); } div2.onclick = function (e) { e.stopPropagation(); alert('div2'); } div3.onclick = function (e) { alert('div3'); } </script>
上面代码默认都是冒泡事件,我们点击div3会依次弹出’div3’与’div2’,为什么没有弹出’div1’这是因为e.stopPropagation();阻止了目标元素的事件继续冒泡到上级。如果每个点击事件都加上了e.topPropagation就不会出现多弹窗的情况。
event.stopPropagation()阻止捕获:
<div> 这是div1 <div> 这是div2 <div>这是div3</div> </div> </div> <script> let div1 = document.getElementById('div1'); let div2 = document.getElementById('div2'); let div3 = document.getElementById('div3'); div1.addEventListener('click',function(e){ console.log('div1'); },true); div2.addEventListener('click',function(e){ console.log('div2'); e.stopPropagation(); },true); div3.addEventListener('click',function(e){ console.log('div3'); },true); </script>
当我们点击div2会依次弹出’div1’与’div2’,这也是因为在div2事件中我们设置了e.stopPropagation(),阻塞了目标元素的事件继续向下捕获。
event.target == event.currentTarget:
div.addEventListener('click',function(e){ if(event.target == event.currentTarget){ //需要执行的代码 } });
此方法不过多解释用的不多,如果你理解了上面的内容,这个方法也能理解。
五、补充:为什么要使用addEventListener()
从上面代码不难看出addEventListener()
有如下的优点(以下是MDN的原话):
addEventListener()
是 W3C DOM 规范中提供的注册事件监听器的方法。它的优点包括:
- 它允许给一个事件注册多个监听器。 特别是在使用AJAX库,JavaScript模块,或其他需要第三方库/插件的代码。
- 它提供了一种更精细的手段控制
listener
的触发阶段。(即可以选择捕获或者冒泡)。 - 它对任何 DOM 元素都是有效的,而不仅仅只对 HTML 元素有效。
六、取消默认事件
event.preventDefault()
默认事件指的是<a href=""></a>
,<input type="submit">
标签这类有默认行为的标签,通过点击可以跳转或提交。我们给这类标签绑定一个点击事件,设置事件对象的preventDefault()方法就可以阻止默认事件的发生。
<a>点击跳转</a> <script> let a = document.querySelector('a'); addEventListener('click',function(e){ e.preventDefault(); }) </script>
那么我们如何才能知道一个标签是否有默认事件,打印事件对象的cancelable属性,通过事件执行就可以知道e.cancelable的结果,如果为false表示有默认事件,true则没有。
return false;
事件执行函数中设置return false
取消默认事件,但此方法不常用。
【相关推荐:javascript学习教程】
The above is the detailed content of Learn more about event bubbling and capturing in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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.

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.

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.

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.

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

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment