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

如何在forEach遍历中实现点击按钮时移除上一个按钮的selected类

解决方案

可以通过以下两种方式实现点击按钮时切换selected类,确保每次只有一个按钮处于选中状态:

方法一:基于现有数组批量处理

在点击事件触发时,先遍历所有按钮移除selected类,再给当前点击的按钮添加该类:

const buttons = ["home","menu","contact"]
buttons.forEach(btn => {
    let button = document.getElementById(btn)
    button.addEventListener('click',()=>{
        // 移除所有按钮的selected类
        buttons.forEach(id => {
            document.getElementById(id).classList.remove('selected')
        })
        // 给当前点击的按钮添加选中类
        button.classList.add('selected')
    })
});

方法二:通过统一类选择器操作

如果所有按钮都有共同的类(比如给每个按钮加上nav-button类),可以直接通过类选择器获取所有按钮,无需依赖原id数组:

注:需要先给HTML中的按钮添加统一类,例如 <button id="home" class="nav-button">首页</button>

const buttons = document.querySelectorAll('.nav-button');
buttons.forEach(btn => {
    btn.addEventListener('click', () => {
        // 移除所有按钮的选中状态
        buttons.forEach(item => item.classList.remove('selected'));
        // 标记当前按钮为选中状态
        btn.classList.add('selected');
    });
});

两种方法都能实现点击新按钮时自动取消上一个按钮的选中状态,保证同一时间只有一个按钮带有selected类。

内容的提问来源于stack exchange,提问作者Hamdan Salih

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:05:20