你可以这样修改代码来实现点击当前元素时,其他元素移除 'active' 类:

let all = document.querySelectorAll('a');

all.forEach(item => item.addEventListener('click', function() {
  // 移除其他元素的 'active' 类
  all.forEach(link => {
    if (link !== this) {
      link.classList.remove('active');
    }
  });

  // 给当前元素添加 'active' 类
  this.classList.add('active');
}));

这段代码会给所有的 <a> 元素添加点击事件监听器。当点击某个元素时,它会先移除其他元素的 'active' 类,然后再给自身添加 'active' 类。

JavaScript实现点击当前元素,其他元素移除 'active' 类

原文地址: https://www.cveoy.top/t/topic/qjAG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录