测验NextQuestion按钮首题可用后续失效,需实现选对才启用按钮
问题原因与解决方法
问题根源
你遇到的核心问题是:切换到第二题后,没有重置选项按钮的状态和事件绑定,同时nextBtn的状态也没有重新初始化,导致后续无法正常启用。第一题能生效是因为页面加载时初始化了一次,但切换题目后没有重复执行初始化逻辑。
解决方案
我们需要统一管理题目加载的逻辑,每次切换题目时重置所有按钮的状态、重新绑定点击事件,并默认禁用nextBtn,只有选中正确答案时才解锁它。
以下是完整的修改示例代码:
1. 定义题目数据(请替换成你的实际题目)
// 示例题目数组,每个对象包含题目、选项、正确答案索引 const questions = [ { question: "JavaScript的创始人是谁?", options: ["布兰登·艾奇", "道格拉斯·克罗克福德", "瑞恩·达尔", "史蒂夫·乔布斯"], correct: 0 // 正确选项是第一个(对应btn1) }, { question: "以下哪个不是JavaScript的数据类型?", options: ["String", "Number", "Boolean", "Float"], correct: 3 // 正确选项是第四个(对应btn4) } ]; // 全局变量:当前题目索引、按钮元素 let currentQuestionIndex = 0; const nextBtn = document.getElementById("nextBtn"); const optionButtons = [ document.getElementById("btn1"), document.getElementById("btn2"), document.getElementById("btn3"), document.getElementById("btn4") ];
2. 题目加载与重置函数
function loadQuestion() { // 1. 默认禁用下一题按钮 nextBtn.disabled = true; // 2. 重置所有选项按钮的样式和可点击状态 optionButtons.forEach(btn => { btn.style.backgroundColor = ""; // 恢复默认背景色 btn.disabled = false; // 允许点击 btn.onclick = () => checkAnswer(btn); // 重新绑定点击事件 }); // 3. 加载当前题目内容(请根据你的HTML结构调整) const currentQ = questions[currentQuestionIndex]; // 示例:假设你有显示题目的元素id为"questionTitle" // document.getElementById("questionTitle").textContent = currentQ.question; // 4. 设置选项按钮的文本 optionButtons.forEach((btn, index) => { btn.textContent = currentQ.options[index]; }); }
3. 答案校验函数
function checkAnswer(clickedBtn) { const currentQ = questions[currentQuestionIndex]; const clickedIndex = optionButtons.indexOf(clickedBtn); if (clickedIndex === currentQ.correct) { // 选对了:按钮变绿,启用下一题按钮,禁用所有选项防止重复点击 clickedBtn.style.backgroundColor = "green"; nextBtn.disabled = false; optionButtons.forEach(btn => btn.disabled = true); } else { // 选错了:按钮变红,禁用当前错误选项,允许用户选其他选项 clickedBtn.style.backgroundColor = "red"; clickedBtn.disabled = true; } }
4. 下一题切换函数
function nextQuestion() { currentQuestionIndex++; if (currentQuestionIndex < questions.length) { // 还有题目,加载下一题 loadQuestion(); } else { // 所有题目完成,修改按钮状态 nextBtn.textContent = "测验完成"; nextBtn.disabled = true; } }
5. 页面加载时初始化第一题
// 页面加载完成后自动加载第一题 window.onload = loadQuestion;
关键修改点
- 新增
loadQuestion函数,每次切换题目时统一重置所有按钮的状态,确保每道题的初始状态一致 - 每次加载题目时默认禁用
nextBtn,只有选对答案才解锁 - 选对答案后禁用所有选项按钮,避免重复操作;选错仅禁用当前错误按钮,允许用户重新选择
- 移除了一次性绑定事件的逻辑,改为每次加载题目时重新绑定,确保新题目选项能正常响应点击
内容的提问来源于stack exchange,提问作者Julia Straszyńska
相关产品推荐
相关产品推荐

