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

dou*_*mer 17 javascript

我想停止将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>
Run Code Online (Sandbox Code Playgroud)

Hoo*_*ing 28

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

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
  }
}
Run Code Online (Sandbox Code Playgroud)

然后更改调用以传递事件:

div id="fooddmenu" onclick="showMenu(event, this);">Click inside this div</div>
Run Code Online (Sandbox Code Playgroud)

  • 它不一定是第一个参数.顺序由HTML中的事件设置决定,例如,如果您使用`onclick ="showMenu(this,event);"`那么第二个参数将是事件数据. (3认同)