如题,看文档中说前者是阻止事件冒泡,后者是阻止所有被定义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
多做了第一件事情,这就是他们之间的区别
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。