JavaScript Quiz代码中函数返回的checkedAnswer值无法更新如何处理
问题根因
你遇到的选中值不更新、始终沿用第一题答题结果的问题,和手动清空变量没有关系,核心错误点如下:
- 全局声明的
allAnss是在页面首次加载完成时,通过document.querySelectorAll('.ansOptions')获取的静态DOM节点列表。后续每次调用loadQuestion重新生成新的radio选项时,这个全局变量始终保留第一题生成的旧节点引用,遍历过程中根本匹配不到后续渲染的新选项,自然永远读到第一题的选中结果。 - 选项渲染的模板字符串存在标签语法错误:闭合标签错写为
</</li>,会导致DOM解析异常。 - label标签的
for属性值和对应radio的id不匹配,导致点击选项文字无法关联选中对应radio。 - 缺少答题边界判断,最后一题提交后会触发数组越界,也没有设计最终得分的展示逻辑。
修复步骤
- 移除全局静态的
allAnss引用,改为在getCheckedAnswer函数内部,每次调用时动态查询当前页面上的最新radio节点,确保拿到的是当前正在展示题目的选项元素。 - 修正选项渲染模板的标签错误,同步修正label的关联属性,确保点击选项文字可以正常选中。
- 补充答题边界判断,所有题目答完后停止加载新题,切换为得分展示状态。
- 增加未选择选项的拦截提示,避免空提交打乱答题逻辑。
修复后的完整可运行代码
"use strict" const questions = [ { question: "whats the full form of HTML", answers: { a: "Hello Text My Language", b: "Hyper text Main Language", c: "Hyper Text Markup Language", d: "Hi There My Luck", }, correctAnswer:"ent-c", }, { question: "whats the full form of CSS", answers: { a: "Cascading Style Sheet", b: "City Site Section", c: "Cyber Section Stand", d: "CycleStand Section", }, correctAnswer:"ent-a", }, { question: "whats the full form of JSON", answers: { a: "Jest Oriented Note", b: "JavaScript Object Notation", c: "Javascript Organised Node", d: "Joomla Of Node", }, correctAnswer:"ent-b", }, { question: "whats the full form of SQL", answers: { a: "Super Query Language", b: "Sorted Queue Line", c: "Superior Query Language", d: "Structured Query Language", }, correctAnswer:"ent-d", }, ]; let quest = document.querySelector('.question'); let quizLIst = document.querySelector('.quiz'); const btn = document.querySelector('.submitBtn'); const scoreDiv = document.querySelector('.scoreCard'); let currentQuestion = 0; let score=0; const loadQuestion = () =>{ quest.innerText=""; quizLIst.innerHTML=""; console.log(questions[currentQuestion].question); quest.innerText = questions[currentQuestion].question; const ansEntries = Object.entries(questions[currentQuestion].answers); for (const [getQ, getA] of ansEntries) { quizLIst.innerHTML += ` <li><input type="radio" class="ansOptions" id="ent-${getQ}" name="ans" value="${getA}"/><label for="ent-${getQ}">${getA}</label></li> `; } } loadQuestion(); const getCheckedAnswer = () =>{ // 动态获取当前页面的最新选项节点,避免静态引用失效 const currentAllOptions = document.querySelectorAll('.ansOptions'); let answer=""; currentAllOptions.forEach((currAns) =>{ if(currAns.checked){ answer = currAns.id; } }); return answer; } btn.addEventListener('click', ()=> { let checkedAnswer = getCheckedAnswer(); // 拦截未选择选项的空提交 if(!checkedAnswer) { alert('请先选择一个选项再提交'); return; } console.log("checked answer is ", checkedAnswer); if(checkedAnswer === questions[currentQuestion].correctAnswer){ console.log("right"); score++; } else{ console.log("wrong"); } currentQuestion++; if(currentQuestion < questions.length){ loadQuestion(); } else { // 全部题目作答完成,展示最终得分 quest.innerText = "答题完成"; quizLIst.innerHTML = ""; btn.style.display = "none"; scoreDiv.innerText = `你的最终得分是:${score} / ${questions.length}`; scoreDiv.style.display = "block"; } })
内容的提问来源于stack exchange,提问作者developer new
相关产品推荐
相关产品推荐

