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

如何实现JavaScript测验选中选项分值汇总计算功能

JavaScript答题测验功能修复方案

核心问题排查(大部分运行异常的根因)

  • 原始HTML只有单题、单选项的静态结构,未适配多题动态渲染逻辑
  • 单选框name属性全局统一,会导致所有题目选项互斥,只能选一个答案
  • 未实现选项分值与DOM的绑定,以及选中状态的收集逻辑

实现步骤

1. 调整HTML结构

补充题目列表容器、提交按钮、总分展示区域:

<!-- 题目渲染容器 -->
<div id="question-container"></div>
<!-- 提交按钮 -->
<button id="submit-btn">提交答案</button>
<!-- 总分展示 -->
<div id="total-score"></div>

原有你提供的题目配置questions数组无需修改,可直接复用。

2. 动态渲染题目与选项

遍历题目配置,给每道题的单选框设置独立name属性,将分值存入value:

const questionContainer = document.getElementById('question-container')
const submitBtn = document.getElementById('submit-btn')
const totalScoreDom = document.getElementById('total-score')

// 渲染所有题目
function renderQuestions() {
  questions.forEach((q, qIndex) => {
    // 生成题目节点
    const qDom = document.createElement('div')
    qDom.className = 'question'
    qDom.innerHTML = `<h3>${q.question}</h3>`
    // 生成该题所有选项
    q.answers.forEach((a) => {
      const label = document.createElement('label')
      label.className = 'option'
      // 每道题的name用题目索引区分,保证同题选项互斥
      label.innerHTML = `
        <input type="radio" name="q-${qIndex}" value="${a.score}" />
        <span class="option-text">${a.text}</span>
      `
      qDom.appendChild(label)
    })
    questionContainer.appendChild(qDom)
  })
}

// 统计总分
function calcTotalScore() {
  let total = 0
  questions.forEach((q, qIndex) => {
    // 查找当前题选中的选项
    const checkedOption = document.querySelector(`input[name="q-${qIndex}"]:checked`)
    if (checkedOption) {
      total += Number(checkedOption.value)
    }
  })
  return total
}

// 绑定提交事件
submitBtn.addEventListener('click', () => {
  const score = calcTotalScore()
  totalScoreDom.innerText = `总得分:${score}`
})

// 页面加载后渲染题目
renderQuestions()

3. 可选优化点

  • 增加未答题校验,提交时判断是否所有题目都已选择
  • 答题过程中实时计算总分,无需点击提交按钮
  • 支持多选题,将type="radio"改为type="checkbox",收集同题多个选中项的分值累加

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 22:36:07