开发者社区> 问答> 正文

jquery事件中的stopPropagation和stopImmediatePropagation有什么区别

如题,看文档中说前者是阻止事件冒泡,后者是阻止所有被定义handler响应。

那么是否可以这么理解,stopPropagation是在原生的DOM事件中阻止了事件向后传递,而stopImmediatePropagation是直接cancel掉了你在jQuery上定义的handler。两者的区别就是,一个在DOM上stop,一个在jQuery里stop?那么stopPropagation岂不是就把stopImmediatePropagation的功能包括了,还需要设计后者干嘛?

展开
收起
小旋风柴进 2016-03-23 13:52:05 2211 0
1 条回答
写回答
取消 提交回答
  • 请看文档里对event.stopImmediatePropagation()的描述:
    `
    Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.
    `
    从这里可以看出,stopImmediatePropagation做了两件事情:
    第一件事:阻止 绑定在事件触发元素的 其他同类事件的callback的运行,看他下面的例子就很明白:

    $("p").click(function(event) {
      event.stopImmediatePropagation();
    });
    $("p").click(function(event) {
      // 不会执行以下代码
      $(this).css("background-color", "#f00");
    });

    第二件事,阻止事件传播到父元素,这跟stopPropagation的作用是一样的。

    所以文档里面还有这么一句话:

    .. this method also stops the bubbling by implicitly calling event.stopPropagation().
    意思是说其实这个方法是调用了stopPropagation()方法的。

    stopImmediatePropagation比stopPropagation多做了第一件事情,这就是他们之间的区别

    2019-07-17 19:10:51
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关课程

更多

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载