Javascript:如何启用stopPropagation? [英] Javascript : How to enable stopPropagation?

查看:378
本文介绍了Javascript:如何启用stopPropagation?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 object.stopPropagation()我可以停止事件冒泡,但如何重新启用?

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

在js中有一个预定义的函数,如 object.startPropagation

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

编辑: strong>

问题是JS记住,如果你点击对象比停止事件冒泡总是即使我不想要它,所以我想停止它:

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:

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


推荐答案

不记得价值了。每次 onclick 被触发时,事件 e 是新的。问题是你总是取消事件冒泡:

It doesn't remember the value at all. The event e is new each time onclick is fired. The problem is you're always cancelling the event bubbling:

if(foo) {
    e.stopPropagation();
} else {
    e.cancelBubble = true;
}




  • e.stopPropagation 是防止事件冒泡的W3C方法

  • e.cancelBubble 是Microsoft
    方法来防止事件冒泡。

    • e.stopPropagation is the W3C method of preventing event bubbling.
    • e.cancelBubble is the Microsoft method to prevent event bubbling.
    • 它们都是一样的。所以你每次都取消事件的冒泡。更多阅读此处

      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;
          }
      }
      

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

      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.

      总而言之,在您的代码中,每次点击后每次都会取消传播。您必须在函数中放置一些标准来确定是否取消元素层次结构中的传播。

      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.

      这篇关于Javascript:如何启用stopPropagation?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆