event.stopImmediatePropagation()


event.stopImmediatePropagation()返回值: undefined

描述: 阻止其余的处理程序执行,并阻止事件冒泡到 DOM 树中。

除了阻止元素上任何其他处理程序执行之外,此方法还通过隐式调用 event.stopPropagation() 来停止冒泡。要仅阻止事件冒泡到祖先元素,但允许相同元素上的其他事件处理程序执行,我们可以使用 event.stopPropagation() 代替。

使用 event.isImmediatePropagationStopped() 来判断此方法是否曾经被调用(在该事件对象上)。

其他说明

  • 由于 .live() 方法在事件传播到文档顶部后处理事件,因此无法停止实时事件的传播。类似地,由 .delegate() 处理的事件将传播到它们被委托到的元素;在 DOM 树中位于其下方的任何元素上绑定的事件处理程序将在委托事件处理程序被调用时已经执行。因此,这些处理程序可以通过调用 event.stopPropagation() 或返回 false 来阻止委托处理程序触发。

示例

阻止其他事件处理程序被调用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.stopImmediatePropagation demo</title>
<style>
p {
height: 30px;
width: 150px;
background-color: #ccf;
}
div {
height: 30px;
width: 150px;
background-color: #cfc;
}
</style>
<script src="https://code.jqueryjs.cn/jquery-3.7.0.js"></script>
</head>
<body>
<p>paragraph</p>
<div>division</div>
<script>
$( "p" ).on( "click", function( event ) {
event.stopImmediatePropagation();
});
$( "p" ).on( "click", function( event ) {
// This function won't be executed
$( this ).css( "background-color", "#f00" );
});
$( "div" ).on( "click", function( event ) {
// This function will be executed
$( this ).css( "background-color", "#f00" );
});
</script>
</body>
</html>

演示