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

标签 javascript html events dom

考虑以下几点:

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

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

最佳答案

使用 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>

关于javascript - 如何使用内联 onclick 属性停止事件传播?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/387736/

相关文章:

javascript - 为什么 hasOwnProperty ('toString' ) 不适用于对象?

javascript - 由于 CORS 问题,无法在 Heroku 上访问 Flask API

javascript - 使用 .innerhtml 输入带有链接的列表

php - 如何使用 PHP 从 MySQL 查询中按升序排列值?

c# - 关键字 'event' 在 C# 中是可选的吗?

jquery - 如何从 Controller 内的事件访问范围?

javascript - 有用的 Node.js 中间件

html - 绝对定位元素的宽度百分比是多少?

iphone - PhoneGap : download & save binary files (mp3s) for iPhone & Android

jQuery 切换类以删除高亮