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

如何为测验Web应用添加答题对错弹窗提示

为测验Web应用添加答题提示功能

需求:点击选项时,在选项下方弹出“CORRECT”或“INCORRECT”的提示消息,仅在点击时显示,页面样式已设置完成,无需额外调整。

现有代码如下:

现有JavaScript代码

const question = document.getElementById("question");
const choices = Array.from(document.getElementsByClassName("choice-text"));

let currentQuestion = {};
let acceptingAnswers = false;
let score = 0;
let questionCounter = 0;
let availableQuestions = [];


let questions = [{
    question: "Commonly used data types DO NOT include:",
    choice1: "1. strings",
    choice2: "2. booleans",
    choice3: "3. alerts",
    choice4: "4. numbers",
    answer: 3
  },
  {
    question: "Arrays in JavaScript can be used to store ______.",
    choice1: "1. numbers and strings",
    choice2: "2. other arrays",
    choice3: "3. booleans",
    choice4: "4. all of the above",

    answer: 4
  },
  {
    question: "String values must be enclosed within _____ when being assigned to variables.",
    choice1: "1. commas",
    choice2: "2. curly brackets",
    choice3: "3. quotes",
    choice4: "4. parentheses",
    answer: 3,
  },
  {
    question: "A very useful tool used during development and debugging for printing content to the debugger is:",
    choice1: "1. JavaScript",
    choice2: "2. terminal/bash",
    choice3: "3. for loops",
    choice4: "4. console.log",
    answer: 4
  },
  {
    question: "Which of the following is a statement that can be used to terminate a loop, switch or label statement?",
    choice1: "1. break",
    choice2: "2. stop",
    choice3: "3. halt",
    choice4: "4. exit",
    answer: 1
  },
];

const CORRECT_BONUS = 10;
const MAX_QUESTIONS = 5;

startGame = () => {
  questionCounter = 0;
  score = 0;
  availableQuestions = [...questions];
  getNewQuestion();

};
getNewQuestion = () => {
  if (availableQuestions.length === 0 || questionCounter >= MAX_QUESTIONS) {
    return window.location.assign('/finished.html');
  }
  questionCounter++;
  const questionIndex = Math.floor(Math.random() * availableQuestions.length);
  currentQuestion = availableQuestions[questionIndex];
  question.innerText = currentQuestion.question;

  choices.forEach(choice => {
    const number = choice.dataset['number'];
    choice.innerText = currentQuestion['choice' + number];
  })

  availableQuestions.splice(questionIndex, 1);

  acceptingAnswers = true;
};

choices.forEach(choice => {
  choice.addEventListener('click', e => {
    if (!acceptingAnswers) return;

    acceptingAnswers = false;
    const selectedChoice = e.target;
    const selectedAnswer = selectedChoice.dataset['number'];

    const classToApply =
      selectedAnswer == currentQuestion.answer ? "correct" : "incorrect";

    selectedChoice.parentElement.classList.add(classToApply);

    setTimeout(() => {
      selectedChoice.parentElement.classList.remove(classToApply);
      getNewQuestion();

    }, 1000);
  });
});

startGame();

现有HTML代码

<section>
  <div class="container">
    <div class="header">
      <div>
        <p>View High scores<i class="fas fa-hand-point-left fa-lg"></i></p>
      </div>
      <div>Time</div>
    </div>
  </div>
  
  <div class="container">
    <div class="box rectangle-2">
      <h2 id="question">What is the answer to this question?</h2>
      <div class="main">
        <div class="questionWrap">
          <div class="options">
            <ul>
              <li class="choice-text" data-number="1">choice 1</li>
              <li class="choice-text" data-number="2">choice 2</li>
              <li class="choice-text" data-number="3">choice 3</li>
              <li class="choice-text" data-number="4">choice 4</li>
            </ul>
          </div>
        </div>
</section>
</div>
</div>
</div>
</section>

解决方案

步骤1:在HTML中添加提示容器

在选项列表的下方新增一个用于显示提示的容器:

<section>
  <div class="container">
    <div class="header">
      <div>
        <p>View High scores<i class="fas fa-hand-point-left fa-lg"></i></p>
      </div>
      <div>Time</div>
    </div>
  </div>
  
  <div class="container">
    <div class="box rectangle-2">
      <h2 id="question">What is the answer to this question?</h2>
      <div class="main">
        <div class="questionWrap">
          <div class="options">
            <ul>
              <li class="choice-text" data-number="1">choice 1</li>
              <li class="choice-text" data-number="2">choice 2</li>
              <li class="choice-text" data-number="3">choice 3</li>
              <li class="choice-text" data-number="4">choice 4</li>
            </ul>
          </div>
          <!-- 新增提示容器 -->
          <div id="feedback" style="display: none;"></div>
        </div>
      </div>
    </div>
  </div>
</section>

步骤2:修改JavaScript代码实现提示逻辑

获取提示容器元素,在点击选项时设置提示内容并显示,切换题目时隐藏提示:

const question = document.getElementById("question");
const choices = Array.from(document.getElementsByClassName("choice-text"));
// 新增:获取提示容器
const feedback = document.getElementById("feedback");

let currentQuestion = {};
let acceptingAnswers = false;
let score = 0;
let questionCounter = 0;
let availableQuestions = [];


let questions = [{
    question: "Commonly used data types DO NOT include:",
    choice1: "1. strings",
    choice2: "2. booleans",
    choice3: "3. alerts",
    choice4: "4. numbers",
    answer: 3
  },
  {
    question: "Arrays in JavaScript can be used to store ______.",
    choice1: "1. numbers and strings",
    choice2: "2. other arrays",
    choice3: "3. booleans",
    choice4: "4. all of the above",

    answer: 4
  },
  {
    question: "String values must be enclosed within _____ when being assigned to variables.",
    choice1: "1. commas",
    choice2: "2. curly brackets",
    choice3: "3. quotes",
    choice4: "4. parentheses",
    answer: 3,
  },
  {
    question: "A very useful tool used during development and debugging for printing content to the debugger is:",
    choice1: "1. JavaScript",
    choice2: "2. terminal/bash",
    choice3: "3. for loops",
    choice4: "4. console.log",
    answer: 4
  },
  {
    question: "Which of the following is a statement that can be used to terminate a loop, switch or label statement?",
    choice1: "1. break",
    choice2: "2. stop",
    choice3: "3. halt",
    choice4: "4. exit",
    answer: 1
  },
];

const CORRECT_BONUS = 10;
const MAX_QUESTIONS = 5;

startGame = () => {
  questionCounter = 0;
  score = 0;
  availableQuestions = [...questions];
  getNewQuestion();

};
getNewQuestion = () => {
  if (availableQuestions.length === 0 || questionCounter >= MAX_QUESTIONS) {
    return window.location.assign('/finished.html');
  }
  questionCounter++;
  const questionIndex = Math.floor(Math.random() * availableQuestions.length);
  currentQuestion = availableQuestions[questionIndex];
  question.innerText = currentQuestion.question;

  choices.forEach(choice => {
    const number = choice.dataset['number'];
    choice.innerText = currentQuestion['choice' + number];
  })

  availableQuestions.splice(questionIndex, 1);
  // 新增:切换题目时隐藏提示
  feedback.style.display = 'none';
  acceptingAnswers = true;
};

choices.forEach(choice => {
  choice.addEventListener('click', e => {
    if (!acceptingAnswers) return;

    acceptingAnswers = false;
    const selectedChoice = e.target;
    const selectedAnswer = selectedChoice.dataset['number'];

    const classToApply = selectedAnswer == currentQuestion.answer ? "correct" : "incorrect";
    // 新增:设置提示文本并显示
    feedback.textContent = selectedAnswer == currentQuestion.answer ? "CORRECT" : "INCORRECT";
    feedback.style.display = 'block';

    selectedChoice.parentElement.classList.add(classToApply);

    setTimeout(() => {
      selectedChoice.parentElement.classList.remove(classToApply);
      getNewQuestion();
    }, 1000);
  });
});

startGame();

功能说明

  • 点击选项后,立即在选项下方显示对应的“CORRECT”或“INCORRECT”提示
  • 保持原有的选项高亮逻辑,1秒后自动切换到下一题
  • 切换题目时自动隐藏提示容器,避免干扰下一题的展示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:40:07