javascript - 如何防止来自父 DOM 的点击事件?
问题描述
说,我有
HTML:
<div onclick="parent()">
<div onclick="child()"></div>
</div>
SCRIPT: {
function parent() {
console.log("I'm your father");
}
function child() {
console.log("You're not my father");
}
在这种情况下,如果我点击子元素,它的父元素也会被点击,所以 parent() child() 都会被调用。如何在不点击其父级的情况下仅调用 child() ?
解决方案
function parent() {
console.log("I'm your father");
}
function child() {
console.log("You're not my father");
window.event.cancelBubble = "true";
}
<div onclick="parent()" style="height : 40px;width:40px; background:blue">
<div onclick="child()" style="height : 10px;width:10px; background:red"></div>
</div>
您可以使用
window.event.cancelBubble = "true"
推荐阅读
- r - 如何查看/计算数据框中的唯一行数
- ruby - 如何在 Ruby 中将浮点数转换为百分比
- javascript - 如何在将鼠标悬停在图像上时显示 .txt 文件中的数据?
- android - 反应原生肖像图像方向不正确
- amazon-web-services - 生成可供任何客户使用的临时 AWS 凭据
- ruby-on-rails - Rails Fields_for 嵌套在表单更改中
- r - 数字后跟连字符
- server - 我收到与 Access-Control-Allow-Origin 相关的错误消息
- c# - 让 WebAPI 控制器向另一个 REST 服务发送 http 请求
- twitter-bootstrap - Bootstrap 4 - 如何添加多个标题,每个标题有多个列?