You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript点击按钮添加active类时如何移除重复的类实例

实现方案
  • 方案1:全量遍历清除(代码简洁,易维护)
    如果你的卡片数量不多(100个以内),直接在点击事件中先清空所有卡片的active类,再给当前点击的卡片添加即可,逻辑简单不易出错:
const giftcards = document.querySelectorAll('.giftcard');

for(let giftcard of giftcards){
  giftcard.onclick = () => {
    giftcards.forEach(card => card.classList.remove('active'));
    giftcard.classList.add('active');
  }
}
  • 方案2:缓存激活元素(性能更优)
    如果卡片数量非常多,可以额外用一个变量存储当前处于激活状态的卡片,每次点击只需要操作上一个激活的卡片和当前点击的卡片,不需要全量遍历:
const giftcards = document.querySelectorAll('.giftcard');
let activeCard = null;

for(let giftcard of giftcards){
  giftcard.onclick = () => {
    activeCard?.classList.remove('active');
    giftcard.classList.add('active');
    activeCard = giftcard;
  }
}

注:上述代码中的可选链运算符?.如果需要兼容旧浏览器,可以替换成if(activeCard) activeCard.classList.remove('active')。

内容的提问来源于stack exchange,提问作者Clay Raymond

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 03:45:04