gpt4 book ai didi

javascript - 如果使用 vanilla Javascript 触发另一个 EventListener,我如何返回或使所有其他 EventListener 为空

转载 作者:行者123 更新时间:2023-11-30 13:45:52 24 4
gpt4 key购买 nike

我想要完成的是一段代码,当单击其中一个按钮时,该按钮将获得下面列出的样式,而所有其他按钮样式将返回 null。

我假设它涉及一个 bool 语句,但也许我错了。

您将在下面看到我试图使用我的“else if”语句来确定当事件目标不等于“button”时,将所有内容返回为 null。但是,这显然行不通。

我也试过“!==”,但没有用。

显然,这可以通过为每个按钮创建一个唯一的事件监听器来完成,但我想弄清楚如何动态地执行此操作。

CSS:

button {
font-family: "sans-serif";
margin: 1%;
padding: 1%;
cursor: pointer;
font-size: 22px;
}

这是我的 html:

<section id="button-container">
<button>a</button>
<button>b</button>
<button>c</button>
<button>d</button>
<button>e</button>
</section>

这是我的 Javascript:

var buttons = document.querySelectorAll('#button-container button');

buttons.forEach(button => {
button.addEventListener("click", function(e) {
if (e.target === button) {
e.target.style.backgroundColor = "blue";
e.target.style.color = "orange";
} else if (e.target != button) {
e.target.style.backgroundColor = null;
e.target.style.color = null;
}
})
})

最佳答案

我不会直接修改样式,而是使用一个类:

button.active {
background-color: blue;
color: orange
}

当你点击一个按钮然后添加 active 类给它:

button.addEventListener("click", function(e) {
this.classList.add("active");
});

我们现在只需添加一些逻辑即可从之前单击的按钮中删除 active 类。

我们可以遍历所有按钮并从所有按钮中删除类:

buttons.forEach(button => button.classList.remove("active"));

或者我们在 DOM 中查询当前“事件”按钮并仅将其从该按钮中删除:

const activeButton = document.querySelector("#button-container button.active");
activeButton.classList.remove("active");

或者我们使用当前按钮的 parentNode 来“搜索”:

const activeButton = button.parentNode.querySelector("button.active");

或者我们使用 .getElementsByClassName() 的“魔法”,它返回具有给定 CSS 的所有元素的实时集合(它将自动更新具有给定类的当前元素集)类:

const buttons = document.querySelector('#button-container');
const activeButtons = document.querySelector("#button-container").getElementsByClassName("active");

/* ... */

button.addEventListener("click", function(ev) {
if (activeButtons.length) {
activeButtons[0].classList.remove("active"); // there should always be only _one_ active button
}

this.classList.add("active");
});

例子:

var buttons = document.querySelectorAll('#button-container button');

buttons.forEach(button => {
button.addEventListener("click", function(e) {
const activeButton = button.parentNode.querySelector("button.active");
if (activeButton) {
activeButton.classList.remove("active");
}

this.classList.add("active");
})
})
button {
font-family: "sans-serif";
margin: 1%;
padding: 1%;
cursor: pointer;
font-size: 22px;
}

button.active {
background-color: blue;
color: orange;
}
<section id="button-container">
<button>a</button>
<button>b</button>
<button>c</button>
<button>d</button>
<button>e</button>
</section>

关于javascript - 如果使用 vanilla Javascript 触发另一个 EventListener,我如何返回或使所有其他 EventListener 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59345927/

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