训练营Trivia项目:如何随机获取问题并实现DOM渲染与答案校验?
问题分析与修复方案
代码核心问题
renderQuestion函数的for循环逻辑完全错误:初始值i = state.questions.length,循环条件i === 0永远不成立,循环体根本不会执行- 未获取DOM元素:
question变量没有通过document.getElementById('question')获取对应label元素 - 存在无限循环风险:while循环没有改变
attempts或切换问题的逻辑,一旦进入会卡死页面 - 缺少提交事件绑定:没有给submit按钮添加点击事件处理用户输入校验
- 未保存当前选中的问题对象:后续校验时无法获取对应问题的正确答案
修复步骤与完整代码
1. 初始化state与测试问题
首先确保state对象存在,并创建测试用的Question实例:
// 初始化全局状态对象 const state = { questions: [], currentQuestion: null // 保存当前显示的问题,方便后续校验答案 }; // 创建测试问题实例 new Question("2+2等于多少?", "4", "简单的加法运算"); new Question("JavaScript的创始人是谁?", "Brendan Eich", "他只用了10天完成JS原型设计"); new Question("HTML的全称是什么?", "HyperText Markup Language", "构建网页结构的标记语言");
2. 修正随机问题与渲染函数
让getRandomQuestion直接返回Question对象,renderQuestion负责更新页面显示:
class Question { constructor(question, answer, hint) { this.question = question; this.answer = answer; this.hint = hint; this.attempts = 3; state.questions.push(this); } } // 随机获取一个Question对象 function getRandomQuestion() { const randomIndex = Math.floor(Math.random() * state.questions.length); return state.questions[randomIndex]; } // 渲染问题到页面 function renderQuestion() { // 获取DOM元素 const questionLabel = document.getElementById('question'); const userInput = document.getElementById('user'); // 选中随机问题并保存到状态 state.currentQuestion = getRandomQuestion(); // 更新label文本 questionLabel.textContent = state.currentQuestion.question; // 清空输入框 userInput.value = ''; }
3. 添加用户输入校验逻辑
给submit按钮绑定点击事件,处理答案校验与尝试次数:
// 校验用户输入的答案 function checkAnswer() { const userInput = document.getElementById('user'); const userAnswer = userInput.value.trim(); if (!state.currentQuestion) return; // 大小写不敏感的答案校验 if (userAnswer.toLowerCase() === state.currentQuestion.answer.toLowerCase()) { alert("答对了!"); renderQuestion(); // 切换到下一个随机问题 } else { state.currentQuestion.attempts--; if (state.currentQuestion.attempts > 0) { alert(`答错了!还有${state.currentQuestion.attempts}次机会,提示:${state.currentQuestion.hint}`); } else { alert(`机会用完了,正确答案是:${state.currentQuestion.answer}`); renderQuestion(); // 切换到下一个随机问题 } } } // 绑定按钮事件 document.getElementById('submit').addEventListener('click', checkAnswer); // 页面加载完成后渲染第一个问题 window.addEventListener('load', renderQuestion);
4. 保留原HTML结构
<form class="current-question"> <label for="userInput" id="question"></label> <input type="text" name="userInput" id="user"> <button type="button" for="userInput" id="submit">Submit</button> </form>
关键改进点
- 用
state.currentQuestion保存当前问题,避免校验时重复随机获取 - 修复DOM元素获取逻辑,确保能正确更新页面内容
- 加入大小写不敏感校验,提升用户体验
- 处理尝试次数耗尽的场景,答对/答错后自动切换新问题
内容的提问来源于stack exchange,提问作者Lacey Washington
相关产品推荐
相关产品推荐

