如何撤消 jQuery 中的 event.stopPropagation?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9324941/
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-27 10:39:34  来源:igfitidea点击:

How to undo event.stopPropagation in jQuery?

eventsjavascript-eventsjquery

提问by Hubro

I'm using event.stopPropagation()in my application. There has appeared, however, one scenario where I want the propagation to continue as if the aforementioned function was never called. So I'm wondering; is there a way to "resume" propagation after it's been stopped? It would be terribly tedious to move the one call to event.stopPropagationto a dozen separate conditional statements.

event.stopPropagation()在我的应用程序中使用。但是,出现了一种情况,我希望传播继续进行,就好像上述函数从未被调用过一样。所以我想知道; 有没有办法在停止传播后“恢复”传播?将一个调用移动event.stopPropagation到十几个单独的条件语句将是非常乏味的。

回答by Schiavini

Once propagation has been stopped, it cannot be resumed. As a workaround, what you can do is set a variable, and then only stop if this variable is true:

传播一旦停止,就无法恢复。作为一种解决方法,您可以做的是设置一个变量,然后仅在该变量为真时停止:

var stop = false;
// do your logic here
if(stop){
    event.stopPropagation();
}

回答by Rory McCrossan

Put the event.stopPropagation()call inside your condition. For example

event.stopPropagation()电话放在你的条件中。例如

$el.click(function(event) {
    if (some_condition) {
        event.stopPropagation()
        // do stuff
    }
    else {
        // do other stuff, without stopping propagation
    }
});

Tedious it may be, but unfortunately stopPropagation is a one way switch. Once stopped, you can't turn it back on for the same event.

它可能很乏味,但不幸的是 stopPropagation 是一种单向切换。一旦停止,您将无法为同一事件重新打开它。

回答by Jeffrey Rosselle

Just refactor your original event like this:

只需像这样重构您的原始事件:

var refEvent = event.originalEvent;
refEvent.cancelBubble = false;
refEvent.defaultPrevented = false;
refEvent.returnValue = true;
refEvent.timeStamp = (new Date()).getTime();

if (event.target.dispatchEvent){
    event.target.dispatchEvent(refEvent);
} else if (event.target.fireEvent) {
    event.target.fireEvent(refEvent);
}

回答by Jsproject

Here is a solution that works:

这是一个有效的解决方案:

$('#mydiv').on('click.new', function(e){

    e.stopImmediatePropagation();

alert('this will happen only once');

$('#mydiv').unbind('click.new');

});

It makes use of the fact that event can have custom namespace, and can unbind accordingly. It also works for e.stopPropagation. For that matter, it can undo anything associated with that custom click event.

它利用了事件可以具有自定义命名空间的事实,并且可以相应地解除绑定。它也适用于e.stopPropagation. 就此而言,它可以撤消与该自定义点击事件相关的任何内容。