如何通过querySelectorAll选中除当前点击项外的所有.menu-item元素?
实现菜单点击切换active类的解决方案
首先你当前代码有两个核心问题:
- 用箭头函数作为点击回调,箭头函数没有独立的
this,导致这里的this不指向点击的菜单项,添加/移除类的操作自然无效。 document.querySelector(".menu-link")只会选中第一个匹配元素,无法批量操作所有菜单项。
关于你想「直接选中除当前项外元素」的需求,有两种可行方案,其中遍历已获取的元素集合是最简洁高效的:
方案一:遍历已有菜单集合(推荐)
既然已经用querySelectorAll拿到了所有.menu-item,直接遍历这个集合移除所有is-active类,再给当前点击项添加即可。代码简洁,且菜单元素数量通常不多,完全不用担心性能问题:
const menu = document.querySelectorAll('.menu-item'); menu.forEach(item => { // 用普通函数做回调,让this指向当前点击的菜单项 item.addEventListener('click', function() { // 移除所有菜单项的is-active类 menu.forEach(menuItem => menuItem.classList.remove('is-active')); // 给当前点击项添加is-active类 this.classList.add('is-active'); }); });
如果你习惯用箭头函数,也可以把当前项存到变量里避免this问题:
const menu = document.querySelectorAll('.menu-item'); menu.forEach(item => { item.addEventListener('click', () => { menu.forEach(menuItem => menuItem.classList.remove('is-active')); item.classList.add('is-active'); }); });
方案二:使用CSS :not()选择器(需临时标识)
如果你坚持想用选择器直接排除当前项,可以给当前项加个临时属性,再用:not()选中其他元素,操作完移除临时属性:
const menu = document.querySelectorAll('.menu-item'); menu.forEach(item => { item.addEventListener('click', function() { // 添加临时属性标记当前项 this.setAttribute('data-current', ''); // 选中所有非当前项的.menu-item,移除is-active document.querySelectorAll('.menu-item:not([data-current])').forEach(el => el.classList.remove('is-active')); // 移除临时属性 this.removeAttribute('data-current'); // 给当前项添加active类 this.classList.add('is-active'); }); });
不过这种方法需要额外的属性操作,反而不如方案一直接实用。
内容的提问来源于stack exchange,提问作者Mayga Fatmawati
相关产品推荐
相关产品推荐

