JavaScript测验脚本开发:实现id=0起始与next_question跳转逻辑
JavaScript 交互测验核心功能实现
前置问题修正
你提供的示例题库存在多处JSON语法偏差,直接加载会触发解析失败,常见问题包括:
- 键值对后误用分号分隔(比如原示例中
id:"0";的分号属于非法语法) - 部分答案列表没有用标准数组结构包裹
- 多余的嵌套括号、数组末尾多余的尾随逗号
修正后的标准可运行题库结构如下:
{ "quiz": [ { "id": "0", "question": "Who is the strongest?", "answers": [ {"name": "btn1", "next_question": "1"}, {"name": "btn2", "next_question": "2"} ] }, { "id": "1", "question": "What is the best site ever created?", "answers": [ {"name": "btn1", "next_question": "0"}, {"name": "btn2", "next_question": "2"} ] }, { "id": "2", "question": "Where is Waldo really?", "answers": [ {"name": "btn1", "next_question": "1"}, {"name": "btn2", "next_question": "2"} ] } ] }
实现逻辑设计
针对你提出的两个核心需求,可按以下逻辑落地:
- 题库加载完成后,提前生成题目索引映射表:把数组形式的quiz题目转成以id为键、题目内容为值的对象,避免每次跳转都遍历数组查找题目,提升运行效率
- 首屏启动逻辑固定读取id为
"0"的题目完成首次渲染,满足“测验始终从id为0的题目启动”的要求 - 渲染题目时为每个答案按钮绑定点击事件,把按钮对应的
next_question参数存入事件回调,点击触发时根据参数值从题目索引中取出对应题目,重新执行渲染流程完成页面内容切换
可直接复用的实现代码
// 加载题库后初始化逻辑 const quizBank = { /* 替换为你实际的JSON题库内容 */ }; // 1. 生成题目索引映射表 const questionMap = quizBank.quiz.reduce((map, question) => { map[question.id] = question; return map; }, {}); // 2. 绑定页面DOM挂载节点 const questionContainer = document.querySelector('#question-area'); const answerContainer = document.querySelector('#answer-area'); // 3. 封装通用题目渲染函数 function renderCurrentQuestion(questionId) { const currentQuestion = questionMap[questionId]; // 渲染题目文本 questionContainer.textContent = currentQuestion.question; // 清空上一题的残留答案 answerContainer.innerHTML = ''; // 动态生成答案按钮并绑定跳转事件 currentQuestion.answers.forEach(answerItem => { const answerBtn = document.createElement('button'); answerBtn.textContent = answerItem.name; answerBtn.addEventListener('click', () => { // 根据答案配置的next_question值加载对应题目 renderCurrentQuestion(answerItem.next_question); }) answerContainer.appendChild(answerBtn); }) } // 4. 启动测验:固定从id为0的题目开始渲染 renderCurrentQuestion('0');
常见注意事项
- 保持题目id、next_question的取值类型统一(比如全部用字符串或者全部用数字),避免因为类型不匹配导致索引查找失败
- 每次渲染新题目前记得清空上一题的DOM内容,避免旧答案残留影响交互
- 可根据实际需求在渲染流程中增加答题计数、得分统计、答题结束判定的逻辑
内容的提问来源于stack exchange,提问作者stray12228
相关产品推荐
相关产品推荐

