如何阻止div中的onclick事件传播到文档? [英] How to stop onclick event in div from propagating to the document?

查看:610
本文介绍了如何阻止div中的onclick事件传播到文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想停止将此div的onclick事件传播到文档?当用户点击div时,两个警报都会出现:1)div的警报和2)文档的警报。我想要取消文档警报。

I want to stop propagation of this div's onclick event to the document? When the user click on the "div", both alerts appear: 1) the div's alert and 2) the document's alert. I want to suppress the document alert.

我知道如何使用addEventListener来做,但还有另一种方法吗?下面的问题是我不知道如何得到事件 - 我尝试了event = element.onclick,如下所示,但这不起作用。我如何参加活动?

I know how to do it using addEventListener, but is there another way to to do it? The problem below is that I don't know how to get ahold of the event -- I tried "event = element.onclick", shown below, but that doesn't work. How do I get the event?

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


推荐答案

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

Change your function definition to include the event:

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

然后更改要传入的调用事件:

Then change the call to pass in the event:

div id="fooddmenu" onclick="showMenu(event, this);">Click inside this div</div>

这篇关于如何阻止div中的onclick事件传播到文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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