首页 > 解决方案 > 如何防止来自父 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() ?

标签: javascripthtmldom

解决方案


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"

推荐阅读