Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

javascript - How to stop onclick event in div from propagating to the document?

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.

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...