event.stopImmediatePropagation()

阻止剩余的事件处理函数的执行,并且防止事件冒泡到 DOM 树上。

除了阻止元素上其它的事件处理函数的执行,这个方法还会通过在内部调用 event.stopPropagation() 来阻止事件冒泡。如果仅仅想要停止事件冒泡到祖先元素上,而让这个元素上的其它事件处理函数继续执行,我们可以使用 event.stopPropagation() 来代替。

使用 event.isImmediatePropagationStopped() 来确定这个方法是否(在那个事件对象上)被调用过。

补充说明:

  • 因为 .live() 事件一旦被传播到文档顶部,就不可能再阻止 live 事件的传播。类似的,通过 .delegate() 执行的事件,也会传播到调用它们的元素上。同时,任何在 DOM 树中,比这些元素低的元素上绑定的相同事件,在 .delegate() 事件被调用的时候,也会被触发。因此,如果要在事件中阻止委托事件被触发,可以通过调用 event.stopPropagation() 方法,或返回 false 的方式来实现。

示例:

阻止调用其它事件处理函数。

<!DOCTYPE html>
<html>
<head>
<style>
p { height: 30px; width: 150px; background-color: #ccf; }
div {height: 30px; width: 150px; background-color: #cfc; }
</style>
<script src="jquery.min.js"></script>
</head>
<body>

<p>paragraph</p>
<div>division</div>

<script>


$("p").click(function(event){
  event.stopImmediatePropagation();
});
$("p").click(function(event){
  // This function won't be executed
  $(this).css("background-color", "#f00");
});  
$("div").click(function(event) {
  // This function will be executed
    $(this).css("background-color", "#f00");
});

</script>
</body>
</html>

演示: