JavaScript答题游戏问题:答完最后一题后无法自动结束
问题解决:答题游戏答完最后一题不自动结束
问题分析
当前代码仅在计时器归0时触发gameOver逻辑,但未判断所有题目是否已完成。答完最后一题后,currentQuestion会超出题目数组索引范围,代码仍尝试调用displayQuestion加载不存在的题目,不会主动结束游戏。
修复步骤
- 将计时器变量改为全局:原
startTimer中的timeInterval是局部变量,无法在外部清除,改为全局声明后,可在答完题时停止计时器。 - 增加题目完成判断:在
nextquestion函数中,每次更新currentQuestion后,检查是否遍历完所有题目,若是则直接触发gameOver并停止计时器。 - 修复计时器文本更新逻辑:原
timerEl是元素集合,直接赋值无效,需通过ID精准获取计时器元素。
修改后的完整代码
JavaScript部分
//calling in id/class from HTML const questionEl = document.getElementById("question") const checkers = document.getElementById("right-wrong") const timerEl = document.getElementById("timeSpan") // 改为直接获取单个元素 const answerOne = document.getElementById("answer1") const answerTwo = document.getElementById("answer2") const answerThree = document.getElementById("answer3") const answerFour = document.getElementById("answer4") const finalScoreEl = document.getElementById("pointScore") const nameEl = document.getElementById("initials") const highScoreEl = document.getElementById("highScoreList") //test question var questionKey = [ { question: "which variable has the value of a string.", choiceOne: "x = 6", choiceTwo: "x = \"87\"", choiceThree: "x = true", choiceFour: "x;", answer: "x = \"87\"" }, { question: "choose the operator that checks for value and type.", choiceOne: "=", choiceTwo: "+=", choiceThree: "===", choiceFour: "<=;", answer: "===" }, { question: "choose the true statement.", choiceOne: "4 != 4", choiceTwo: "4 > 85", choiceThree: "7 === \"7\"", choiceFour: "7.6 == \"7.6\"", answer: "7.6 == \"7.6\"" }, { question: "which data type is not primitive.", choiceOne: "boolean", choiceTwo: "array", choiceThree: "number", choiceFour: "string", answer: "array" }, { question: "Which one is the Increment operator.", choiceOne: "**", choiceTwo: "/", choiceThree: "++", choiceFour: "+=", answer: "++" } ]; //starting positions let timeLeft = 60; let score = 0; let currentQuestion = -1 let finalScore; let timeInterval; // 全局计时器变量 //change div to start the test function changeDiv(curr, next) { document.getElementById(curr).classList.add('hide'); document.getElementById(next).removeAttribute('class') }; //button to start the game document.querySelector('#startButton').addEventListener('click', gameStart); function gameStart() { changeDiv('start', 'questionHolder'); currentQuestion = 0; displayQuestion(); startTimer(); }; //timer function/Count down function startTimer() { timeInterval = setInterval( () => { timeLeft--; timerEl.textContent = timeLeft; if (timeLeft <= 0) { clearInterval(timeInterval); gameOver(); } }, 1000); }; function displayQuestion() { questionEl.textContent = questionKey[currentQuestion].question answerOne.textContent = questionKey[currentQuestion].choiceOne answerTwo.textContent = questionKey[currentQuestion].choiceTwo answerThree.textContent = questionKey[currentQuestion].choiceThree answerFour.textContent = questionKey[currentQuestion].choiceFour } //handle next question and game end document.querySelector('#questionHolder').addEventListener('click', nextquestion); function nextquestion(event) { if (event.target.className === "btn") { // 判断答案对错 if (event.target.textContent === questionKey[currentQuestion].answer) { score += 10; } else { if (timeLeft >= 10) { timeLeft -= 10; timerEl.textContent = timeLeft; } else { timeLeft = 0; clearInterval(timeInterval); gameOver(); return; // 提前退出,避免后续执行 } } currentQuestion++; // 检查是否所有题目已完成 if (currentQuestion >= questionKey.length) { clearInterval(timeInterval); gameOver(); } else { displayQuestion(); } } }; //game over logic function gameOver() { timerEl.textContent = 0; changeDiv('questionHolder', 'finishedPage'); finalScore = score; finalScoreEl.textContent = finalScore; };
HTML部分(无需修改)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>The coding quiz</title> <link rel="stylesheet" href="./Main/style.css"> </head> <body> <header> <div id="pageTop"> <h1>The coding quiz</h1> </div> </header> <div id="scoreTime"> <p class="highscore"><a href="./highscore/index.html">View highscores</a></p> <p class="timer">Time left: <span id="timeSpan">60</span></p> </div> <div id="quizHolder"> <div id="start"> <h2>Basic Code Quiz</h2> <p>Welcome to the basic coding quiz, this quiz will test you knoweledge on basic javascript.</p> <button id="startButton" class="btn">Start</button> </div> <div id="questionHolder" class="hide"> <h2 id="question"></h2> <button id="answer1" class="btn"></button> <button id="answer2" class="btn"></button> <button id="answer3" class="btn"></button> <button id="answer4" class="btn"></button> </div> <div id="finishedPage" class="hide"> <h2>Quiz Complete</h2> <p>Your final score is <span id="pointScore"></span>/50</p> <label>Enter your initials:</label> <input type="text" id="initials"> <button id="sendScore" class="btn">Submit score</button> </div> </div> <script src="Main/script.js"></script> </body> </html>
关键修改点说明
- 全局声明
timeInterval:确保在答完所有题目时能停止计时器,避免计时器继续倒计时。 - 增加题目完成判断:在
nextquestion中检查currentQuestion >= questionKey.length,当所有题目答完后直接调用gameOver,不再尝试加载不存在的题目。 - 修复计时器元素获取:将
getElementsByClassName改为getElementById,确保能正确更新计时器显示文本。
内容的提问来源于stack exchange,提问作者Bryce Bann
相关产品推荐
相关产品推荐

