在线测验系统难度筛选后首题显示HTML占位符问题排查求助
问题根源分析
看起来问题出在测验启动时没有主动渲染第一道题目——你当前的代码只在点击「Submit」按钮触发nextQuestion时才会替换题目内容,但启动测验后显示的是HTML里的原始占位文本,并没有被更新。
具体来说:
- 你的
startQuiz函数(虽然没贴出完整代码)应该只是显示了question-holder容器,但没有对初始的.quiz元素执行内容替换 nextQuestion的逻辑是移除现有题目、克隆模板再渲染新题目,但这只在点击按钮后触发,第一次启动时的初始占位文本完全没被处理
解决方案
1. 完善startQuiz函数,启动时直接渲染第一道题
首先确保启动测验时,立刻根据选中的难度渲染第一道随机题目:
function startQuiz() { // 显示题目容器 const questionHolder = document.getElementById('question-holder'); questionHolder.classList.remove('hide'); // 重置计数器(假设你有这些全局变量) questionCounter = 0; score = 0; // 渲染第一道题 renderQuestion(); } function renderQuestion() { // 筛选对应难度的题目 const filteredQuestions = questions.filter( question => question.difficulty === difficultyLevel ); // 处理无可用题目的边界情况 if (filteredQuestions.length === 0) { document.querySelector('#question').innerText = 'No questions available for selected difficulty.'; return; } // 随机选一道题 const randomIndex = Math.floor(Math.random() * filteredQuestions.length); const selectedQuestion = filteredQuestions[randomIndex]; // 直接更新页面上的quiz元素(第一次启动用初始的,之后用克隆的) const quizElement = document.querySelector('.quiz'); displayQuestion(quizElement, selectedQuestion); }
2. 调整nextQuestion逻辑,复用渲染函数
把渲染逻辑抽成独立的renderQuestion函数后,nextQuestion可以简化,避免重复代码:
function nextQuestion() { if (questionCounter >= maxQuestion) { endQuiz(); return; } increaseQuestionCounter(); // 移除旧题目,克隆模板添加新的(保留你原有的DOM操作逻辑) const quizTemplate = document.querySelectorAll(".quiz")[0]; const quizParent = quizTemplate.parentNode; quizParent.removeChild(quizTemplate); const newQuizElement = quizTemplate.cloneNode(true); quizParent.appendChild(newQuizElement); // 渲染新题目 renderQuestion(); }
3. 额外优化:默认难度设置
为了避免用户没选难度就启动测验,建议在页面加载时默认选中一个难度,或者在startQuiz里做检查:
// 页面加载时默认选中easy难度 window.addEventListener('load', () => { document.getElementById('easy-diff').checked = true; difficultyLevel = 'easy'; });
快速验证点
- 启动测验前,先在控制台打印
difficultyLevel,确认它和你选中的难度一致 - 打印
filteredQuestions.length,确认能筛选出对应难度的题目数量
内容的提问来源于stack exchange,提问作者Huey O'Brien
相关产品推荐
相关产品推荐

