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 03:56

There are two ways to get the event object from inside a function:

  1. The first argument, in a W3C-compliant browser (Chrome, Firefox, Safari, IE9+)
  2. The window.event object in Internet Explorer (<=8)

If you need to support legacy browsers that don't follow the W3C recommendations, generally inside a function you would use something like the following:

function(e) {
  var event = e || window.event;
  [...];
}

which would check first one, and then the other and store whichever was found inside the event variable. However in an inline event handler there isn't an e object to use. In that case you have to take advantage of the arguments collection which is always available and refers to the complete set of arguments passed to a function:

onclick="var event = arguments[0] || window.event; [...]"

However, generally speaking you should be avoiding inline event handlers if you need to to anything complicated like stopping propagation. Writing your event handlers separately and the attaching them to elements is a much better idea in the medium and long term, both for readability and maintainability.

查看更多
临风纵饮
3楼-- · 2018-12-31 03:57

Use this function, it will test for the existence of the correct method.

function disabledEventPropagation(event)
{
   if (event.stopPropagation){
       event.stopPropagation();
   }
   else if(window.event){
      window.event.cancelBubble=true;
   }
}
查看更多
ら面具成の殇う
4楼-- · 2018-12-31 03:57

I had the same issue - js error box in IE - this works fine in all browsers as far as I can see (event.cancelBubble=true does the job in IE)

onClick="if(event.stopPropagation){event.stopPropagation();}event.cancelBubble=true;"
查看更多
几人难应
5楼-- · 2018-12-31 03:59

According to this page, in IE you need:

event.cancelBubble = true

查看更多
柔情千种
6楼-- · 2018-12-31 04:01

For ASP.NET web pages (not MVC), you can use Sys.UI.DomEvent object as wrapper of native event.

<div onclick="event.stopPropagation();" ...

or, pass event as a parameter to inner function:

<div onclick="someFunction(event);" ...

and in someFunction:

function someFunction(event){
    event.stopPropagation(); // here Sys.UI.DomEvent.stopPropagation() method is used
    // other onclick logic
}
查看更多
笑指拈花
7楼-- · 2018-12-31 04:04

Use event.stopPropagation().

<span onclick="event.stopPropagation(); alert('you clicked inside the header');">something inside the header</span>

For IE: window.event.cancelBubble = true

<span onclick="window.event.cancelBubble = true; alert('you clicked inside the header');">something inside the header</span>
查看更多
登录 后发表回答