本文讲解如何通过索引控制和数组遍历,动态渲染多道选择题,并配合按钮实现“下一题”功能,涵盖状态管理、dom更新与事件绑定等核心要点。
本文讲解如何通过索引控制和数组遍历,动态渲染多道选择题,并配合按钮实现“下一题”功能,涵盖状态管理、dom更新与事件绑定等核心要点。
在构建交互式测验应用时,关键在于
有序遍历题目数组
并
按需渲染当前题目及其选项
。下面是一个结构清晰、可直接运行的完整实现方案。
✅ 核心思路
使用 currentQuestion 全局变量跟踪当前题号(从 0 开始);
每次点击「下一题」时,递增索引并取模循环(或重置为 0),确保不越界;
利用 forEach() 遍历当前题的 answers 数组,动态填充预设按钮内容;
为每个答案按钮添加点击逻辑(如高亮正确答案、禁用交互等,本例聚焦切换逻辑)。
? 完整 HTML + JavaScript 示例
⚠️ 注意事项与优化建议
避免硬编码 ID
:生产环境推荐动态创建按钮(document.createElement),而非依赖固定 ID;
状态隔离
:将 currentQuestion 封装进闭包或使用模块化设计,防止全局污染;
边界防护
:% questions.length 比手动 if/else 重置更简洁且天然支持任意数量题目;
可访问性
:为按钮添加 aria-label,并考虑键盘导航支持;
样式增强
:为 .answer-btn 添加 CSS(如 margin: 4px; padding: 8px 12px;)提升用户体验。
掌握数组遍历与 DOM 动态更新的结合方式,是构建前端交互式内容的基础能力——本例虽简,却已覆盖核心范式。
Eclipse导入Android或其他的JAVA项目的正确方法 WORD版
本文档主要讲述的是Eclipse导入Android或其他的JAVA项目的正确方法;希望本文档会给有需要的朋友带来帮助;感兴趣的朋友可以过来看看
下载
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 currentQuestion = 0;
const questionDiv = document.getElementById('question');
const answerBtns = ['1', '2', '3', '4'].map(id => document.getElementById(id));
function displayQuestions() {
// 更新题号:循环切换(0 → 1 → 0 → …)
currentQuestion = (currentQuestion + 1) % questions.length;
// 渲染题目标题(序号从 1 开始显示)
questionDiv.textContent = `${currentQuestion + 1}. ${questions[currentQuestion].question}`;
// 遍历当前题的所有答案,填入对应按钮
questions[currentQuestion].answers.forEach((answer, index) => {
if (answerBtns[index]) {
answerBtns[index].textContent = answer.Text;
// 可选:绑定点击响应(例如判断对错)
answerBtns[index].onclick = () => handleAnswerClick(answer.correct);
}
});
}
// 示例:点击答案后的处理逻辑(可扩展)
function handleAnswerClick(isCorrect) {
alert(isCorrect ? '✅ 正确!' : '❌ 再想想~');
}