gpt4 book ai didi

javascript - 如何阻止来自父 DOM 的点击事件?

转载 作者:行者123 更新时间:2023-11-28 14:34:37 24 4
gpt4 key购买 nike

说,我有

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"

关于javascript - 如何阻止来自父 DOM 的点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50227767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com