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

如何将e.target.value转为变量并实现PHQ9测试分数汇总?

解决PHQ9问卷分数收集与总分计算问题

首先要修正你HTML里的一个问题:循环生成的<select>都用了同一个id="options",这违反了HTML规范(id必须唯一),会导致后续DOM操作出现意外问题。建议改成动态生成唯一id,或者直接用class选择器,示例如下:

<ol id="questionList">
  {% for question in questions %}
  <li class="questions">{{question.question}}</li>
  <!-- 用循环索引生成唯一id,同时添加统一class用于选择 -->
  <select id="question-{{loop.index}}" class="form-select form-select-lg mb-3 question-select">
    <option selected>Please select an option</option>
    <option value="0">Not at all</option>
    <option value="1">Several days</option>
    <option value="2">More than half the days</option>
    <option value="3">Nearly every day</option>
  </select>
  {% endfor %}
</ol>
<!-- 添加按钮触发总分计算,以及显示结果的元素 -->
<button id="calcTotalBtn">计算总分</button>
<p>当前总分:<span id="totalScore">0</span></p>

接下来用JavaScript实现分数存储与总分计算逻辑:

// 初始化分数数组,长度与问题数量一致,初始值设为0
const selectElements = document.querySelectorAll('#questionList .question-select');
const scores = new Array(selectElements.length).fill(0);

// 给每个下拉框绑定change事件,更新对应位置的分数
selectElements.forEach((select, index) => {
  select.addEventListener('change', (e) => {
    // 将选中的字符串值转为数字
    const selectedNum = parseInt(e.target.value, 10);
    // 仅当选中有效数值时更新数组(排除默认未选择项)
    if (!isNaN(selectedNum)) {
      scores[index] = selectedNum;
    }
  });
});

// 定义计算总分的函数
function calculateTotal() {
  // 用reduce累加数组所有元素
  const total = scores.reduce((sum, score) => sum + score, 0);
  // 更新页面显示的总分
  document.getElementById('totalScore').textContent = total;
  // 同时打印到控制台
  console.log('当前总分:', total);
  return total;
}

// 给按钮绑定点击事件触发计算
document.getElementById('calcTotalBtn').addEventListener('click', calculateTotal);

// 如果需要实时计算(每次选择后自动更新总分),可在change事件末尾调用calculateTotal()

核心逻辑说明:

  • 分数数组scores:通过索引与每个问题一一对应,确保分数存储位置准确。
  • 数值转换:用parseInt()将下拉框的字符串值转为数字,避免字符串拼接导致的计算错误。
  • 有效值过滤:用!isNaN()排除默认未选择的选项(该选项无value,转数字会得到NaN)。
  • 总分计算:利用数组reduce()方法快速累加所有分数,逻辑简洁高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 15:18:03