JavaScript代码中count变量无法递增问题排查求助
问题排查:为什么count分数变量无法递增?
我帮你找出了几个核心问题,这就是count始终不增加的原因:
1. 引用了未定义的变量index
在你的提交按钮点击事件里,判断答案是否正确时用了questions[index].answer,但你从头到尾都没定义过index变量!当前正在展示的题目索引是i,所以应该替换成questions[i].answer,不然这个比较条件永远不成立。
2. 错误地检查了span元素的checked属性
你写的document.getElementById("o1").checked完全搞错了对象:o1是用来显示选项文本的<span>标签,只有radio单选框(id为aa、bb、cc、dd的input元素)才有checked属性。span元素根本没有这个属性,所以这几个if判断的条件永远是false,count自然不会递增。
3. 额外的边界小问题
当所有题目做完后,你调用了show(i),但此时i已经等于题目数组的长度,questions[i]是undefined,会导致控制台报错,应该在判断完i > questions.length-1后直接return,不要再执行show(i)。
修正后的完整点击事件代码
document.getElementById("sub").onclick = function() { // 正确检查每个radio的选中状态,并和当前题目的答案比较 if (document.getElementById("aa").checked && questions[i].a === questions[i].answer) { count++; } if (document.getElementById("bb").checked && questions[i].b === questions[i].answer) { count++; } if (document.getElementById("cc").checked && questions[i].c === questions[i].answer) { count++; } if (document.getElementById("dd").checked && questions[i].d === questions[i].answer) { count++; } // 清空单选框选中状态 document.getElementById("aa").checked = false; document.getElementById("bb").checked = false; document.getElementById("cc").checked = false; document.getElementById("dd").checked = false; i++; if (i > questions.length - 1) { // 优化:直接修改现有页面的样式,而不是用document.write覆盖整个页面 document.body.style.backgroundColor = 'red'; const scoreDiv = document.createElement('div'); scoreDiv.textContent = `Your score is: ${count}`; document.body.appendChild(scoreDiv); // 禁用按钮防止重复点击 this.disabled = true; return; // 终止函数,避免执行后面的show(i) } show(i); }
可选优化:简化答案判断逻辑
你可以给每个radio单选框加上value属性,比如:
<input type="radio" id="aa" name="options" value="aaa"/> <input type="radio" id="bb" name="options" value="bbb"/> <input type="radio" id="cc" name="options" value="ccc"/> <input type="radio" id="dd" name="options" value="ddd"/>
这样点击事件里的判断逻辑可以简化成:
const selectedOption = document.querySelector('input[name="options"]:checked'); if (selectedOption && selectedOption.value === questions[i].answer) { count++; }
这样代码更简洁,也不容易出错。
内容的提问来源于stack exchange,提问作者mkp24
相关产品推荐
相关产品推荐

