Javascript:如何启用stopPropagation?

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

Javascript : How to enable stopPropagation?

javascripteventsevent-bubblingevent-propagation

提问by Adam

With object.stopPropagation()I can stop event bubbling but how can I re-enable it?

随着object.stopPropagation()我能阻止事件冒泡,但我怎么能重新启用它?

Is there a pre defined function in js something like object.startPropagation?

在 js 中是否有预定义的函数之类的object.startPropagation

EDIT:

编辑:

The Problem is that the JS remembers if you click on the "object" than stop Event Bubbling always even after I don't want it, so I would like to stop it:

问题是 JS 记得如果你点击“对象”而不是在我不想要它之后总是停止事件冒泡,所以我想停止它:

document.getElementById("object").onclick = function(e){
    if(e && e.stopPropagation) {
        e.stopPropagation();
    } else {
          e = window.event;
          e.cancelBubble = true;
    }
}

回答by djdd87

It doesn't remember the value at all. The event eis new each time onclickis fired. The problem is you're alwayscancelling the event bubbling:

它根本不记得值。e每次onclick触发时该事件都是新的。问题是你总是取消事件冒泡:

if(foo) {
    e.stopPropagation();
} else {
    e.cancelBubble = true;
}
  • e.stopPropagationis the W3C method of preventing event bubbling.
  • e.cancelBubbleis the Microsoft method to prevent event bubbling.
  • e.stopPropagation是 W3C 防止事件冒泡的方法。
  • e.cancelBubble是 Microsoft 防止事件冒泡的方法。

They're both the same. So you're cancelling bubbling of events every time. More reading here.

他们都是一样的。所以你每次都在取消事件的冒泡。更多阅读在这里

You'll need to change your method so that it only cancels bubbling if your criteria are met:

您需要更改您的方法,以便仅在满足您的条件时才取消冒泡:

document.getElementById("object").onclick = function(e) {

    if(e && e.stopPropagation && someCriteriaToStopBubbling === true) 
    {
        e.stopPropagation();
    } 
    else if (someCriteriaToStopBubbling === true)
    {
          e = window.event;
          e.cancelBubble = true;
    }
}

UPDATE:Bear in mind that in your current code, if (e && e.stopPropagation)will always be true if the browser supports stopPropagation. If it goes into the second brace for cancelBubble, it will not remember the value last set. See this fiddle.

更新:请记住,在您当前的代码中,if (e && e.stopPropagation)如果浏览器支持stopPropagation. 如果它进入第二个大括号 for cancelBubble,它将不会记住上次设置的值。看到这个小提琴

Basically, to summarise, in your code you're cancelling propagation every time after every click. You have to put some criteria into the function to determine whether or not to cancel the propagation up the element hierarchy.

基本上,总而言之,在您的代码中,您每次点击后都会取消传播。您必须在函数中加入一些条件来确定是否取消向上元素层次结构的传播。