How to stop event propagation with inline onclick

2018-12-31 03:29发布

Consider the following:

<div onclick="alert('you clicked the header')" class="header">
  <span onclick="alert('you clicked inside the header');">something inside the header</span>
</div>

How can I make it so that when the user clicks the span, it does not fire the div's click event?

11条回答
栀子花@的思念
2楼-- · 2018-12-31 04:05

Keep in mind that window.event is not supported in FireFox, and therefore it must be something along the lines of:

e.cancelBubble = true

Or, you can use the W3C standard for FireFox:

e.stopPropagation();

If you want to get fancy, you can do this:

function myEventHandler(e)
{
    if (!e)
      e = window.event;

    //IE9 & Other Browsers
    if (e.stopPropagation) {
      e.stopPropagation();
    }
    //IE8 and Lower
    else {
      e.cancelBubble = true;
    }
}
查看更多
十年一品温如言
3楼-- · 2018-12-31 04:09

Why not just check which element was clicked? If you click on something, window.event.target is assigned to the element which was clicked, and the clicked element can also be passed as an argument.

If the target and element aren't equal, it was an event that propagated up.

function myfunc(el){
  if (window.event.target === el){
      // perform action
  }
}
<div onclick="myfunc(this)" />
查看更多
还给你的自由
4楼-- · 2018-12-31 04:12
<div onclick="alert('you clicked the header')" class="header">
  <span onclick="alert('you clicked inside the header'); event.stopPropagation()">
    something inside the header
  </span>
</div>
查看更多
萌妹纸的霸气范
5楼-- · 2018-12-31 04:19

This worked for me

<script>
function cancelBubble(e) {
 var evt = e ? e:window.event;
 if (evt.stopPropagation)    evt.stopPropagation();
 if (evt.cancelBubble!=null) evt.cancelBubble = true;
}
</script>

<div onclick="alert('Click!')">
  <div onclick="cancelBubble(event)">Something inside the other div</div>
</div>
查看更多
皆成旧梦
6楼-- · 2018-12-31 04:21

This also works - In the link HTML use onclick with return like this :

<a href="mypage.html" onclick="return confirmClick();">Delete</a>

And then the comfirmClick() function should be like:

function confirmClick() {
    if(confirm("Do you really want to delete this task?")) {
        return true;
    } else {
        return false;
    }
};
查看更多
登录 后发表回答