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

如何在JavaScript中点击激活单个链接并取消其他链接激活状态?

解决方案

你的问题在于点击新链接时,只给当前元素加了active类,但没有移除其他链接的active类,所以所有被点击过的元素都会保持激活状态。按下面的方式修改代码即可实现排他激活:

let parentT = document.querySelector('.menu-item');
let allEl = parentT.querySelectorAll('a');

allEl.forEach(elem => {   
  elem.addEventListener('click', (event) => { 
    event.preventDefault(); 
    // 先移除所有链接的active类
    allEl.forEach(item => item.classList.remove('active'));
    // 给当前点击的链接添加active类
    event.target.classList.add('active');
    // 验证当前元素状态的正确写法
    if(event.target.classList.contains('active')) { 
      console.log(event.target);
    }
  }); 
});

关键改动说明:

  • 新增allEl.forEach(item => item.classList.remove('active')):点击任何链接时,先统一清除所有链接的激活状态
  • 把setAttribute('class', 'active')改成classList.add('active'):避免覆盖元素原有的其他类名(如果存在的话)
  • 把event.target.classList == "active"改成event.target.classList.contains('active'):classList是DOM对象,不能直接和字符串比较,要用contains方法判断是否包含指定类

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:06:05