如何为列表项添加selected类并点击切换时移除其他项的该类?
列表项点击切换选中状态的实现方案
嘿,我来帮你完成这个点击切换选中的功能,先把你的代码补全并优化一下,两种实现方式供你选择~
简单实现版(适合选项数量不多的场景)
这种方式代码简洁直接,每次点击时先移除所有选项的selected类,再给当前点击的项添加类:
const timeRangeWrapper = document.querySelector('.time-range'); const timeOptions = timeRangeWrapper.querySelectorAll('.times .time-option'); timeOptions.forEach((item) => { item.addEventListener('click', () => { // 遍历所有选项,移除选中类 timeOptions.forEach(opt => opt.classList.remove('selected')); // 给当前点击的选项添加选中类 item.classList.add('selected'); // 如果需要获取当前项的data-item值,可以在这里添加 const selectedIndex = item.getAttribute('data-item'); console.log('选中的项索引:', selectedIndex); }); });
性能优化版(适合选项较多的场景)
如果你的列表选项数量比较多,每次遍历所有元素会有点浪费性能,我们可以记录上一个选中的元素,只操作它和当前点击的元素:
const timeRangeWrapper = document.querySelector('.time-range'); const timeOptions = timeRangeWrapper.querySelectorAll('.times .time-option'); // 初始化记录上一个选中的元素,如果页面默认有选中项,这里可以直接获取 let lastSelectedItem = timeRangeWrapper.querySelector('.time-option.selected'); timeOptions.forEach((item) => { item.addEventListener('click', () => { // 如果存在上一个选中的元素,移除它的选中类 if (lastSelectedItem) { lastSelectedItem.classList.remove('selected'); } // 给当前点击的元素添加选中类 item.classList.add('selected'); // 获取当前项的data-item值(按需使用) const selectedIndex = item.getAttribute('data-item'); console.log('选中的项索引:', selectedIndex); // 更新上一个选中元素的记录 lastSelectedItem = item; }); });
额外提示
- 记得在CSS里定义好
.selected类的样式,比如背景色、字体加粗/变色等,这样选中状态才能直观显示出来,示例:
.time-option.selected { background-color: #007bff; color: white; border-radius: 4px; }
内容的提问来源于stack exchange,提问作者Umar
相关产品推荐
相关产品推荐

