HTML/JavaScript单题展示型选择题测验开发问题求助
解决选择题测验的四个核心问题
问题1:切换下一题时,之前选中的Radio Button未取消选中
直接清空答题容器的内容再渲染新题,比手动取消选中更可靠:
function renderQuestion(currentIndex) { const questionContainer = document.getElementById('question-container'); // 先清空容器,彻底清除旧的radio元素 questionContainer.innerHTML = ''; const question = questions[currentIndex]; // 渲染题目文本 const questionText = document.createElement('h3'); questionText.textContent = `${currentIndex + 1}. ${question.text}`; questionContainer.appendChild(questionText); // 渲染选项 question.options.forEach(option => { const label = document.createElement('label'); const radio = document.createElement('input'); radio.type = 'radio'; radio.name = 'answer'; radio.value = option.value; // 新radio默认就是未选中,不需要额外设置checked=false label.appendChild(radio); label.appendChild(document.createTextNode(option.text)); questionContainer.appendChild(label); questionContainer.appendChild(document.createElement('br')); }); }
问题2:提交时第二题得分未计入总分
需要用数组存储每道题的用户选择,最后遍历计算总分,而不是只依赖当前题的选择:
// 全局数组存储每道题的答案,索引对应题目序号 let userAnswers = new Array(questions.length).fill(null); // 切换题目时保存当前题的选择 function saveCurrentAnswer(currentIndex) { const selectedRadio = document.querySelector('input[name="answer"]:checked'); if (selectedRadio) { userAnswers[currentIndex] = selectedRadio.value; } } // 计算总分函数 function calculateScore() { let score = 0; questions.forEach((question, index) => { if (userAnswers[index] === question.correctAnswer) { score++; } }); alert(`总分:${score}/${questions.length}`); }
调用顺序:切换题目前先调用saveCurrentAnswer(currentIndex),提交时调用calculateScore()。
问题3:添加新问题后第二题显示8个Radio、第三题不显示
这是因为渲染时没有清空容器,导致旧选项和新选项叠加,同时可能存在索引越界问题。确保:
- 渲染每道题前必须清空答题容器(参考问题1的代码)
- 检查题目切换的索引逻辑,防止索引越界:
let currentQuestionIndex = 0; function nextQuestion() { saveCurrentAnswer(currentQuestionIndex); currentQuestionIndex++; // 超出最后一题时禁止切换 if (currentQuestionIndex >= questions.length) { alert('已经是最后一题了'); currentQuestionIndex = questions.length - 1; return; } renderQuestion(currentQuestionIndex); }
问题4:添加radiobutton.checked = false;后Radio无法生成
大概率是代码顺序错误,比如在创建Radio元素之前就调用了这个语句,或者变量名拼写错误。正确的做法是:
- 不需要额外设置
checked=false,因为新创建的Radio默认就是未选中状态 - 如果必须手动设置,要在创建元素之后操作:
// 正确顺序 const radio = document.createElement('input'); radio.type = 'radio'; radio.name = 'answer'; radio.value = option.value; // 这行是可选的,因为默认就是false radio.checked = false;
如果之前的代码是在document.createElement之前就给radiobutton赋值,会导致变量未定义,元素无法生成。
内容的提问来源于stack exchange,提问作者Rob
相关产品推荐
相关产品推荐

