在javascript中,我试图在单击按钮时应用'活动'类。然而,我想从以前有它的按钮中删除类。我不知道该怎么做才好。我正在考虑在点击后进行第二次循环,但这似乎有点复杂,可能有更好的方法。下面是我必须添加类的代码,但是,再次,不确定如何最好地将它从以前应用它的按钮中删除。
const giftcards = document.querySelectorAll('.giftcard');
for(let giftcard of giftcards){
giftcard.onclick = () => {
giftcard.classList.add('active');
}
}
如果总是最多有一个具有active
类的.giftcard
,您可以在使用document.querySelector('.giftcard.active')
将active
设置为当前单击的礼品卡之前查询该礼品卡,并使用可选链接(?.)仅在发现元素时删除active
类。
const giftcards = document.querySelectorAll('.giftcard');
for (let giftcard of giftcards) {
giftcard.onclick = () => {
document.querySelector('.giftcard.active')?.classList.remove('active');
giftcard.classList.add('active');
}
}
.active {
color: red;
}
<div class="giftcard">card 1</div>
<div class="giftcard">card 2</div>
<div>
<button class="giftcard">Button 1</button>
<button class="giftcard">Button 1</button>
<button class="giftcard">Button 1</button>
</div>
<script>
const giftcards = document.querySelectorAll(".giftcard");
giftcards.forEach((giftcard) => {
giftcard.addEventListener("click", () => {
giftcardClick(giftcard);
});
});
function giftcardClick(giftcard) {
giftcards.forEach((giftcard) => {
giftcard.classList.remove("active");
});
giftcard.classList.add("active");
}
</script>