如何停止div中的onclick事件传播到文档?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (51)

如何将这个div的onclick事件传播到文档中?当用户点击“div”时,出现两种警报:1)div的警报和2)文档的警报。

如何使用addEventListener来做到这一点,但还有另一种方法来做到这一点?

下面的问题是,我尝试了“event = element.onclick”,如下所示,但这不起作用。我如何获得该活动?

<head>
<script>
  function showMenu(element) {
      alert("div clicked");
      event = element.onclick;  // HOW TO GET HOLD OF THE EVENT?
      // Don't propogate the event to the document
      if (event.stopPropagation) {
          event.stopPropagation();   // W3C model
      } else {
          event.cancelBubble = true; // IE model
      }
  }

  document.onclick = function() {
      alert('document clicked');
  };
</script>
</head>

<body>
  <div id="foodmenu" onclick="showMenu(this);">Click inside this div</div>
  or click outside the div.
</body>
提问于
用户回答回答于

更改函数定义以包含事件:

function showMenu(event, element) {
  alert("div clicked");
  // Don't propogate the event to the document
  if (event.stopPropagation) {
      event.stopPropagation();   // W3C model
  } else {
      event.cancelBubble = true; // IE model
  }
}

改变函数以传递事件:

div id="fooddmenu" onclick="showMenu(event, this);">Click inside this div</div>
用户回答回答于

尝试EventListeners:

HTML:

<div id="fooddmenu">Click inside this div</div>or click outside the div.​​​​​​​​​​

JS:

function showMenu(e) {
    alert("div clicked");
}

document.onclick = function() {
    alert('document clicked');
};

window.onload = function(){
    document.getElementById("fooddmenu").addEventListener("click", function(e){
        showMenu(this);
        e.stopPropagation();

    });
};

扫码关注云+社区

领取腾讯云代金券