jQuery 事件中stoppropagation和stopimmediatepropagation的区别

来源:互联网 发布:mac excel怎么加 编辑:程序博客网 时间:2024/05/22 09:58

原文链接:https://segmentfault.com/q/1010000000120125


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


0 0