gpt4 book ai didi

javascript - 嵌套按钮 : how to achieve separate functionality

转载 作者:行者123 更新时间:2023-11-30 14:56:46 24 4
gpt4 key购买 nike

我有一个按钮附加到父按钮:

var parent_button = document.createElement("button");
var child_button = document.createElement("button");
parent_button.appendChild(child_button);

我想为 child_button 创建独立于 parent_button 的功能:

parent_button.onclick = function () {
//do stuff
};

child_button.onclick = function () {
//do some other stuff
};

但是鉴于这段代码,每当我点击 child_button 时,我必然会触发 parent_button.onclick()。如何区分两者?

重叠的按钮看起来像这样:

enter image description here

最佳答案

在子按钮的事件对象上使用stopPropagation()。它将阻止事件从子级传播到父级。

你可以在这里看到一个例子:

var pb = document.getElementById("pb");
var cb = document.getElementById("cb");
pb.addEventListener("click", function(e) {
console.log("Parent");
});
cb.addEventListener("click", function(e) {
console.log("Child");
e.stopPropagation();
})
<button id="pb">Parent Button <button id="cb">Child Button</button></button>

注意:我认为默认行为是当你点击一个子元素时,应该触发子元素和父元素的事件,但在这个例子中,这并没有发生;也许这对于作为 parent 的按钮来说是特别的。

关于javascript - 嵌套按钮 : how to achieve separate functionality,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47128678/

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