You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Quiz项目checkAnswer函数仅首题验证正确,如何适配后续题目?

Quiz项目checkAnswer函数问题排查思路提示

我在Bootcamp的Quiz项目中开发checkAnswer函数,用于验证玩家选择的答案,相关代码如下:

const startButton = document.querySelector(".start") as HTMLButtonElement;
startButton.addEventListener("click", () => {
  const presentation = document.querySelector(
    ".presentation"
  ) as HTMLDivElement;
  presentation.style.display = "none";
  questionContainer.style.display = "flex";
  displayQuestion(questions[currentQuestion]);
  console.log("je marche");
  checkAnswer(questions[currentQuestion].correctAnswer);
});

function checkAnswer(correctAnswer: string) {
  buttonListener(button1, correctAnswer);
  buttonListener(button2, correctAnswer);
  buttonListener(button3, correctAnswer);
  buttonListener(button4, correctAnswer);
}

function buttonListener(button: HTMLButtonElement, correctAnswer: string) {
  button.addEventListener("click", () => {
    if (button.textContent === correctAnswer) {
      console.log(`${button.textContent} is the right answer`);
      score += 10;
      currentQuestion++;
      button.textContent = "";
      console.log(
        `The current score is ${score} and the next question is number ${
          currentQuestion + 1
        }`
      );
      displayQuestion(questions[currentQuestion]);
      console.log(currentQuestion);
    } else if (button.textContent !== correctAnswer) {
      console.log(`${button.textContent} is not the right answer`);
      score -= 5;
      currentQuestion++;
      button.textContent = "";
      console.log(
        `The current score is ${score} and the next question is number ${
          currentQuestion + 1
        }`
      );
      displayQuestion(questions[currentQuestion]);
      console.log(currentQuestion);
    }
  });
}

当前现状

  • 点击选项按钮后会自动显示下一题,该行为符合预期;
  • 第一题能正确验证答案,但第二题及后续题目中选择正确答案时会被判定错误。

问题推测

切换到第二题后,正确答案未更新,仍在与第一题的正确答案做对比。

已尝试方法

在displayQuestion和checkAnswer函数中创建变量修改正确答案,但均无效。

排查思路提示

  1. 检查事件监听的重复绑定问题:每次调用checkAnswer时,是否给按钮叠加绑定了新的点击事件?后续触发按钮时,旧的回调函数是否还在执行?
  2. 审视correctAnswer的作用域:绑定事件时传入的correctAnswer是固定值,后续切换题目后,回调函数是否依然引用的是第一次传入的那个值?
  3. 考虑动态获取正确答案的方式:是否可以让按钮的点击回调不依赖绑定阶段传入的correctAnswer,而是在触发时直接获取当前显示题目的正确答案?
  4. 尝试清理旧事件监听:在加载新题目之前,移除按钮上已有的点击监听,避免旧逻辑干扰新题目的验证。

内容的提问来源于stack exchange,提问作者OrhanMA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 07:57:33