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

如何实现点击新评分项时自动取消原选中项的class?

解决评分组件单选问题

原代码的问题在于用了toggle方法,只会单独切换当前点击元素的选中状态,不会处理其他已选中的选项,所以会出现多个评分数字同时被选中的情况。

要实现“点击新评分自动取消旧选中”的效果,只需要在每次点击时先清空所有选项的选中状态,再给当前点击的选项加上选中类即可:

const choices = document.querySelectorAll(".choice");

choices.forEach(choice => {
  choice.addEventListener("click", function handleClick(event) {
    // 移除所有选项的选中状态
    choices.forEach(item => item.classList.remove("choice-active"));
    // 给当前点击的选项添加选中状态
    this.classList.add("choice-active");
  });
});

如果还需要支持“点击当前已选中的评分取消选中”的功能,可以加个简单判断:

const choices = document.querySelectorAll(".choice");

choices.forEach(choice => {
  choice.addEventListener("click", function handleClick(event) {
    const isCurrentlyActive = this.classList.contains("choice-active");
    
    // 先清空所有选中状态
    choices.forEach(item => item.classList.remove("choice-active"));
    
    // 只有当前选项原本没选中时,才添加选中状态
    if (!isCurrentlyActive) {
      this.classList.add("choice-active");
    }
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:06:29