Javascript 如何阻止 jQuery 中的事件冒泡?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4522257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:46:10  来源:igfitidea点击:

How to stop events bubbling in jQuery?

javascriptjqueryjquery-eventsevent-bubbling

提问by Stann

How do I stop custom event bubbling in jQuery?

如何在 jQuery 中停止自定义事件冒泡?

For example I have this code:

例如我有这个代码:

$('.myclass').bind('amodaldestroy', function(){
    ....does something.....
})

How do I only allow this to be triggered once on the first element it finds when bubbling? Can I just add return false?

我如何只允许在冒泡时找到的第一个元素上触发一次?我可以添加 returnfalse吗?

$('.myclass').bind('amodaldestroy', function(){
     ....does something.....
    return false;
})

回答by Daniel T.

According to jQuery's documentation:

根据 jQuery 的文档

$('myclass').bind('amodaldestroy'), function(event) {
    ....does something....
    event.stopPropagation();
});

回答by Russ Cam

Use event.stopPropagation();

event.stopPropagation();

$('.myclass').bind('amodaldestroy', function(e){
    e.stopPropagation();
});

You can also use return falsebut there is a subtle difference between the two in that returning false also calls event.preventDefault();

您也可以使用,return false但两者之间存在细微差别,即返回 false 也调用event.preventDefault();

回答by David Sherret

For support in IE < 9:

对于 IE < 9 的支持:

$(".element").click(function(e)
{
    var event = e || window.event;
    event.stopPropagation ? event.stopPropagation() : (event.cancelBubble=true);
});

回答by kobe

This might not be that great but

这可能不是那么好,但是

return false;

return falsewill do both stopPropagationand event.preventDefault...

return false将两者都做stopPropagation,并event.preventDefault...

if you want only one you can choose based on your choice

如果你只想要一个,你可以根据你的选择进行选择

please read this , this is from SO only

请阅读此内容,仅来自 SO

return falseis effectively both preventDefault and stopPropogation.

return false实际上是 preventDefault 和 stopPropogation。

preventDefaultwill prevent the default event from occuring, stopPropogation will prevent the event from bubbling up and return false will do both.

preventDefault将阻止默认事件发生,stopPropogation 将阻止事件冒泡,返回 false 将两者兼而有之。