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

开发产品匹配测验时如何根据radio单选框输入累加变量并求出最大值

实现方案

第一步:优化HTML结构

同一组单选框需要用相同name属性关联,同时避免重复id导致的交互异常,修改后示例:

<!-- 第1题的单选组 -->
<input class="answer__input" type="radio" name="question1" value="product1" />
<input class="answer__input" type="radio" name="question1" value="product2" />
<input class="answer__input" type="radio" name="question1" value="product3" />
<input class="answer__input" type="radio" name="question1" value="product4" />

<!-- 后续题目只需修改name属性即可,比如第2题设为name="question2" -->

第二步:JavaScript实现逻辑

建议用对象存储产品计数,比单独声明4个变量更易维护,完整代码如下:

// 初始化产品计数
const productScores = {
  product1: 0,
  product2: 0,
  product3: 0,
  product4: 0
}

// 给所有单选框绑定选择事件
document.querySelectorAll('.answer__input').forEach(radio => {
  radio.addEventListener('change', function() {
    // 选中后对应产品分数+1
    const selectedProduct = this.value
    productScores[selectedProduct]++
  })
})

// 测验结束后调用这个函数获取匹配度最高的产品
function getTopProduct() {
  // 把计数对象转成数组,按分数从高到低排序
  const sortedProducts = Object.entries(productScores).sort((a, b) => b[1] - a[1])
  // 取最高分数,兼容并列第一的情况
  const maxScore = sortedProducts[0][1]
  const topProducts = sortedProducts.filter(item => item[1] === maxScore).map(item => item[0])
  return topProducts
}

调用示例

测验结束后直接调用getTopProduct()即可得到结果:

  • 如果分数为product1=2、product2=4、product3=3、product4=1,调用后返回 ["product2"]
  • 如果有多个产品分数相同且都是最高,会返回所有并列的产品,比如product2和product3都是4分,返回 ["product2","product3"]

如果你必须保留原来声明的四个独立var变量,可把事件监听里的赋值逻辑改为window[selectedProduct]++,全局声明的var变量会自动挂载到window对象上,也可以实现计数效果,但更推荐对象存储的方案,可扩展性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:54:04