本文介绍如何使用 javascript 遍历嵌套结构的题目数组,实现点击“下一题”按钮后动态更新题目内容和选项按钮,并确保逻辑健壮、变量清晰、dom 操作安全。
本文介绍如何使用 javascript 遍历嵌套结构的题目数组,实现点击“下一题”按钮后动态更新题目内容和选项按钮,并确保逻辑健壮、变量清晰、dom 操作安全。
在构建交互式测验(Quiz)应用时,核心挑战之一是有序遍历题目数组并动态渲染每道题及其选项。原始代码存在多个关键问题:变量命名混乱(如 nextQuestionindex 与 QI 拼写错误/语义不明)、循环逻辑错误(试图用 for...of 字符串索引误操作答案)、事件监听器未完成、且缺少对边界条件(如最后一题后回环或终止)的处理。
下面是一个结构清晰、可维护性强的实现方案:
✅ 正确思路概览
- 使用单一状态变量 currentQuestionIndex 跟踪当前题号(从 0 开始);
- 每次点击“下一题”时,先递增索引,再校验是否越界(可选择循环回到第 1 题,或停在末尾);
- 清空并重建所有选项按钮(避免残留事件或旧内容),而非复用固定 ID 按钮(更灵活、可扩展);
- 为每个选项按钮绑定点击事件,后续可扩展为答案反馈、计分等逻辑。
✅ 完整可运行示例
<!-- HTML 结构 --> <div id="quiz-container"> <h2 id="question"></h2> <div id="answers"></div> <button id="next-btn">下一题</button> </div>
// 题目数据(保持原结构)
const questions = [
{
question: "Commonly used data types DO NOT include:",
answers: [
{ Text: 'strings', correct: false },
{ Text: 'booleans', correct: false },
{ Text: 'alerts', correct: true },
{ Text: 'numbers', correct: false }
]
},
{
question: 'The condition in an if else statement is enclosed within:___',
answers: [
{ Text: 'parentheses', correct: true },
{ Text: 'curly brackets', correct: false },
{ Text: 'numbers and strings', correct: false },
{ Text: 'square brackets', correct: false }
]
}
];
// 状态管理
let currentQuestionIndex = 0;
const questionEl = document.getElementById('question');
const answersEl = document.getElementById('answers');
const nextBtn = document.getElementById('next-btn');
// 渲染当前题目及选项
function displayQuestion() {
const currentQ = questions[currentQuestionIndex];
// 更新题干(带序号)
questionEl.textContent = `${currentQuestionIndex + 1}. ${currentQ.question}`;
// 清空旧选项
answersEl.innerHTML = '';
// 动态创建选项按钮
currentQ.answers.forEach((answer, idx) => {
const btn = document.createElement('button');
btn.textContent = answer.Text;
btn.className = 'btn answer-btn';
btn.dataset.index = idx; // 记录选项索引,便于后续判断正确性
btn.addEventListener('click', () => {
const isCorrect = answer.correct;
console.log(`你选择了:“${answer.Text}” → ${isCorrect ? '✅ 正确' : '❌ 错误'}`);
// 此处可添加高亮、禁用按钮、显示解析等交互
});
answersEl.appendChild(btn);
});
}
// “下一题”点击处理
nextBtn.addEventListener('click', () => {
currentQuestionIndex = (currentQuestionIndex + 1) % questions.length;
displayQuestion();
});
// 初始化首题
displayQuestion();
⚠️ 关键注意事项
- 避免全局污染:将 currentQuestionIndex 等状态封装在闭包或模块中,长期项目建议使用类或 React 等状态管理方案;
- DOM 安全性:始终校验 questions[currentQuestionIndex] 是否存在,防止 undefined 报错(本例用取模 % 自动循环,亦可用 if (currentQuestionIndex >= questions.length) return; 终止);
- 可访问性增强:为按钮添加 role="button" 和键盘支持(如 Enter 触发),符合 WCAG 标准;
- 样式与体验:建议为 .answer-btn 添加 CSS 过渡效果,并在用户点击后临时禁用按钮,防止重复提交。
通过以上实现,你不仅解决了“如何循环数组并展示题目”的技术问题,更构建了一个可扩展、易调试、符合现代前端实践的测验基础框架。










