分支逻辑测验无法跳转至下一题:问题排查求助
树形分支逻辑测验问题修复
问题根源分析
- 数据结构与遍历逻辑不匹配:你的
questions数组是树形嵌套结构(子问题在选项的question字段中),但代码用questionIndex递增的方式线性遍历数组,而数组仅包含1个元素,questionIndex++后直接超出范围,导致读取undefined的question属性报错。 - showQuestion函数错误:直接将
questions[questionIndex]赋值给questionText(这是个对象,不是文本),同时choices是数组,不能直接通过.label访问选项文本。 - 变量作用域冲突:
beginQuiz函数内重复声明let questionIndex = 0,覆盖了全局的questionIndex变量,导致后续逻辑中索引值混乱。 - 事件绑定冗余+逻辑错误:既在全局给按钮绑定了
nextQuestion,又在beginQuiz里重复绑定点击事件,且没有根据用户选择的选项跳转到对应子问题,只是盲目递增索引。
修复方案
1. 调整核心逻辑:跟踪当前问题节点
放弃用索引遍历数组,改为维护当前的currentQuestion变量,每次根据用户选择的选项,跳转到该选项对应的子问题。
2. 修正函数实现
- 移除冗余的事件绑定,统一在初始化时处理。
- 修复
showQuestion函数,正确读取问题文本和选项。 - 移除
beginQuiz内的局部questionIndex,使用全局变量或直接用currentQuestion。
完整修复代码
const questions = [ { question: { text: 'What type of wine do you like?', choices: [ { label: 'white', path: 1, question: { text: 'I prefer...', choices: [ { label: 'sparkling', path: 11, // 可添加结果信息,比如result: "推荐起泡白葡萄酒" }, { label: 'still', path: 12, // result: "推荐静止白葡萄酒" }, ], }, }, { label: 'red', path: 2, question: { text: 'I prefer...', choices: [ { label: 'sparkling', path: 21, // result: "推荐起泡红葡萄酒" }, { label: 'still', path: 22, // result: "推荐静止红葡萄酒" }, ], }, }, ], }, }, ]; // 全局维护当前问题节点 let currentQuestion; // 初始化测验 function beginQuiz() { // 从第一个问题开始 currentQuestion = questions[0].question; showQuestion(); // 绑定按钮点击事件(仅绑定一次) topBtn.addEventListener('click', () => handleChoice(0)); bottomBtn.addEventListener('click', () => handleChoice(1)); restartBtn.addEventListener('click', restart); } // 显示当前问题 function showQuestion() { // 显示问题文本 questionText.innerHTML = currentQuestion.text; // 显示选项 topBtn.innerHTML = currentQuestion.choices[0].label; bottomBtn.innerHTML = currentQuestion.choices[1].label; } // 处理用户选择的选项 function handleChoice(choiceIndex) { const selectedChoice = currentQuestion.choices[choiceIndex]; // 如果该选项有子问题,切换到子问题 if (selectedChoice.question) { currentQuestion = selectedChoice.question; showQuestion(); } else { // 没有子问题,显示结果页 showResult(selectedChoice); } } // 显示结果(需根据需求自定义) function showResult(choice) { questionText.innerHTML = `你的选择是${choice.label},推荐对应的葡萄酒!`; // 可隐藏按钮或显示结果相关内容 topBtn.style.display = 'none'; bottomBtn.style.display = 'none'; } // 重启测验 function restart() { beginQuiz(); topBtn.style.display = 'block'; bottomBtn.style.display = 'block'; } // 启动测验 beginQuiz();
关键修复点说明
- currentQuestion变量:用来跟踪当前显示的问题节点,每次用户选择选项后,直接切换到该选项的
question字段(如果存在)。 - handleChoice函数:替代原来的
nextQuestion,根据用户点击的选项索引(0或1)获取对应选择项,判断是否有子问题,决定切换问题还是显示结果。 - 移除冗余事件绑定:避免重复绑定导致的逻辑混乱,仅在初始化时绑定一次按钮事件。
- 修复showQuestion函数:正确读取
currentQuestion的文本和选项数组中的标签。
内容的提问来源于stack exchange,提问作者Arcturus
相关产品推荐
相关产品推荐

