一尘不染

JavaScript如何使用内联onclick属性停止事件传播?

javascript

考虑以下:

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

如何做到这一点,以便当用户单击范围时不会触发div的click事件?


阅读 405

收藏
2020-04-25

共1个答案

一尘不染

使用event.stopPropagation()。

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

对于IE: window.event.cancelBubble = true

<span onclick="window.event.cancelBubble = true; alert('you clicked inside the header');">something inside the header</span>
2020-04-25