小编典典

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

all

考虑以下:

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

我怎样才能做到这一点,当用户点击跨度时,它不会触发div的点击事件?


阅读 99

收藏
2022-04-02

共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>
2022-04-02