当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


JQuery event.stopImmediatePropagation()用法及代码示例

用法
event.stopImmediatePropagation() => undefined

说明:阻止其余的处理程序被执行,并防止事件在 DOM 树中冒泡。

  • 添加的版本:1.3event.stopImmediatePropagation()

    • 此方法不接受任何参数。

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

使用 event.isImmediatePropagationStopped() 了解是否曾调用过此方法(在该事件对象上)。

其他注意事项:

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

例子:

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

<!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.jquery.com/jquery-3.5.0.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>

演示:

相关用法


注:本文由纯净天空筛选整理自jquery.com大神的英文原创作品 event.stopImmediatePropagation()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。