javascript event bubbling and capturing (再谈一谈js的事件冒泡和事件补获,看到这篇文章加深了理解)
原文地址:http://javascript.info/tutorial/bubbling-and-capturing
先给出最终的结论:
Summary
- Events first are captured down to deepest target, then bubble up. In IE<9 they only bubble.
- All handlers work on bubbling stage excepts
addEventListener
with last argumenttrue
, which is the only way to catch the event on capturing stage. - Bubbling/capturing can be stopped by
event.cancelBubble=true
(IE) orevent.stopPropagation()
for other browsers.
bubbling:
DOM elements can be nested inside each other. And somehow, the handler of the parent works even if you click on it’s child.
The reason is event bubbling.
For example, the following DIV
handler runs even if you click a nested tag like EM
or CODE
:
< div onclick = "alert('Div handler worked!')" > |
< em >Click here triggers on nested < code >EM</ code >, not on < code >DIV</ code ></ em > |
</ div > |
That’s because an event bubbles from the nested tag up and triggers the parent.
The main principle of bubbling states:
After an event triggers on the deepest possible element, it then triggers on parents in nesting order.
For example, there are 3 nested divs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!DOCTYPE HTML> <html> <body> <link type= "text/css" rel= "stylesheet" href= "example.css" > <div class = "d1" >1 <!-- the topmost --> <div class = "d2" >2 <div class = "d3" >3 <!-- the innermost --> </div> </div> </div> </body> </html> |
The bubbling guarantees that click on Div 3
will trigger onclick
first on the innermost element 3 (also caled the target), then on the element 2, and the last will be element 1.
The order is called a bubbling order, because an event bubbles from the innermost element up through parents, like a bubble of air in the water.
this
and event.target
The deepest element which triggered the event is called the target or, the originating element.
Internet Explorer has the srcElement
property for it, all W3C-compliant browsers use event.target
. The cross-browser code is usually like this:
var target = event.target || event.srcElement |
When handlers trigger on parents:
event.target/srcElement
- remains the same originating element.this
- is the current element, the one event has bubbled to, the one which runs the handler.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现