首页 > 开发 > JS > 正文

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

2017-09-05 13:02:29  来源:网友分享

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

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

解决方案

请看文档里对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多做了第一件事情,这就是他们之间的区别