event.stopImmediatePropagation()
阻止剩余的事件处理函数执行并且防止事件冒泡到DOM树上。
event.stopImmediatePropagation()
- 这个方法不接受任何参数。
除了阻止元素上其它的事件处理函数的执行,这个方法还会通过在内部调用event.stopPropagation()
来停止事件冒泡。如果仅仅想要停止事件冒泡到祖辈元素上,而让这个元素上的其它事件处理函数继续执行,我们可以使用 event.stopPropagation()
来代替。
使用 event.isImmediatePropagationStopped()
来确定这个方法是否(在那个事件对象上)调用过了。
Additional Notes:(其他注意事项:)
- 自从
.live()
方法处理事件一旦传播到文档的顶部,live事件是不可能停止传播的。同样地,.delegate()
事件将始终传播给其中包含的被委托元素;元素上的事件将在被委托事件被调用的时候执行。因此,这些处理程序,可以调用event.stopPropagation()
或者返回false
防止委派处理程序冒泡。例子
阻止调用其它事件处理函数。
<!DOCTYPE html> <html> <head> <style> p { height: 30px; width: 150px; background-color: #ccf; } div {height: 30px; width: 150px; background-color: #cfc; } </style> <script src="https://www.lanmper.cn/static/js/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>
paragraph
division