This article was initially published in Http://szhshp.org
Reprint Please specify
Event snapping and bubbling
The first catch is necessarily the parent node, then a layer of layers is captured down, then a layer of layers bubbles up
Here is a TD to be clicked on
Through three stages:
- Capture phase: From parent node, gradually bubbles to the target node, that is, from top to bottom
- Close to the target elem phase (this phase activates both the first and third stages of handler)
- Bubbling phase: Bubbling from child nodes to parent nodes
Event binding mechanism
onXXX(event)
addEventListener(event, handler)
- jquery's
elem.on(event, selector, handler)
Here are a few things to keep in mind:
event.target
: The elem that initiated the event
this
: Current Elem
onXXX()
addEventListener(event, handler)
events that pass or bind are not accessible 捕捉阶段
, they only respond to the second and third stages
- In addition, for
addEventListener(event, handler)
the last function:
false
: Handler placed in bubbling phase
true
: Handler placed in capture phase
- Just for
elem.on(event, selector, handler)
, you only need to return false
be able to block default events and prevent bubbling
Stop bubbling
It is generally not necessary to block bubbling, since blocking bubbles may affect other event snapping mechanisms
The core of organizational bubbling is this function:event.stopPropagation()
Events will not continue to pass after the bubble is blocked
The following paragraph will not be called to body
theonclick
<body onclick="alert(`the bubbling doesn‘t reach here`)"> <button onclick="event.stopPropagation()">Click me</button> <!-- 错误的例子,这个仅仅阻止了默认事件 --> <!-- <button onclick="return false;">Click me</button> --></body>
Several other ways to prevent bubbling:
// 既阻止冒泡, 又阻止默认事件, 仅仅对于`elem.on(event, selector, handler)`有效// $("#div1").on(‘click‘,function(){// return false;// });//以下两种情况阻止事件冒泡//oEvent.cancelBubble = true;//oEvent.stopPropagation();//以下两种情况阻止默认行为, 没有停止冒泡//没有停止冒泡//oEvent.preventDefault(); //return false;
Reference documents
Https://javascript.info/bubbling-and-capturing
You don't know anything. JavaScript (5): HTML event capture and bubbling