How to stop event propagation with inline onclick attribute?

2022-08-29 23:44:28

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 's click event?div


答案 1

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>

答案 2

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 object to use. In that case you have to take advantage of the collection which is always available and refers to the complete set of arguments passed to a function:earguments

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.