首页 > 解决方案 > 单击按钮后程序两次进入 eventListener

问题描述

下午好。单击“开始”按钮后,我正在呈现带有答案的测验的第一个问题。Next questions render only when the answer in a previous question is chosen. 问题是当第一个问题被呈现时,它的答案会出现两次。我做了一些调试,由于某些原因,在我单击按钮后,程序两次进入 addEventListener,这就是为什么只有在第一个问题中我有重复的答案,后来一切正常。这是代码,也是可以看到这个包的网站dnd1993.github.io

const button = document.querySelector('.quiz_info__btn');
const quizInfo = document.querySelector('.quiz_info');
const quiz = document.querySelector('.quiz');
const answers_container = document.querySelector('.answers__container');
const check = document.querySelectorAll('.answers__container__answer');
const question_number = document.querySelector('h3');
const quiz_question = document.querySelector('h2');
const image = document.querySelector('.quiz__img');
const resultDescription = document.querySelector('.quiz__results-description');
let currentQuestion = 0;
let correctAnswers = 0;

const questions = [
  {
    question: 'Which Hogwarts class has a different teacher every year?',
    answers: [
      { text: 'Potions', correct: false },
      { text: 'Defence Against The Dark Arts', correct: true },
      { text: 'Herbology', correct: false },
      { text: 'Flying', correct: false },
    ],
  },
  {
    question: 'Who was Hermione’s date at the Yule Ball in The Goblet of Fire?',
    answers: [
      { text: 'Harry Potter', correct: false },
      { text: 'Cedric Diggory', correct: false },
      { text: 'Victor Krum', correct: true },
      { text: 'Neville Longbottom', correct: false },
    ],
  },
  {
    question: 'Where is Azkaban located?',
    answers: [
      { text: 'Past the Forbidden Forest, turn right', correct: false },
      { text: 'In a dark corner across the earth', correct: false },
      { text: 'The North Sea', correct: true },
      { text: 'Diagon Alley', correct: false },
    ],
  },
  {
    question: 'How did Harry and Ron get to Hogwarts in Chamber of Secrets?',
    answers: [
      { text: 'The flying Ford Anglia', correct: true },
      { text: 'Hogwarts Express', correct: false },
      { text: 'Nimbus 2000', correct: false },
      { text: 'The Knight Bus', correct: false },
    ],
  },
  {
    question: 'What is Tom Riddle’s middle name?',
    answers: [
      { text: 'Bilius', correct: false },
      { text: 'Marvolo', correct: true },
      { text: 'Percival', correct: false },
      { text: 'Voldemort', correct: false },
    ],
  },
  {
    question: 'Where can Hogwarts students visit from their third year?',
    answers: [
      { text: 'Godric’s Hollow', correct: false },
      { text: 'Hogsmeade', correct: true },
      { text: 'Spinner’s End', correct: false },
      { text: 'Gringotts', correct: false },
    ],
  },
  {
    question: "Who do we find out is Harry's godfather in Prisoner of Azkaban?",
    answers: [
      { text: 'Tom Riddle', correct: false },
      { text: 'Severus Snape', correct: false },
      { text: 'Albus Dumbledore', correct: false },
      { text: 'Sirius Black', correct: true },
    ],
  },
  {
    question: "What colour are Dobby's eyes?",
    answers: [
      { text: 'Blue', correct: false },
      { text: 'Brown', correct: false },
      { text: 'Black', correct: false },
      { text: 'Green', correct: true },
    ],
  },
  {
    question: 'What shape birthmark does Dumbledore have?',
    answers: [
      { text: 'A phoenix', correct: false },
      { text: 'A map of the London Underground', correct: true },
      { text: 'The key to Hogwarts', correct: false },
      { text: 'A perfect heart', correct: false },
    ],
  },
  {
    question:
      'Which of these is a Potterwatch Radio alter-ego in the Deathly Hallows?',
    answers: [
      { text: 'Lupin', correct: false },
      { text: 'Rapier', correct: true },
      { text: 'Pansy', correct: false },
      { text: 'Rolanda', correct: false },
    ],
  },
  {
    question: 'Which Horcrux was the first one to be destroyed?',
    answers: [
      { text: 'Marvolo Gaunt’s ring', correct: false },
      { text: 'Tom Riddle’s diary', correct: true },
      { text: 'Nagini', correct: false },
      { text: 'Helga Hufflepuff’s Cup', correct: false },
    ],
  },
  {
    question: "What is the number of Harry's vault at Gringotts?",
    answers: [
      { text: '687', correct: true },
      { text: '492', correct: false },
      { text: '384', correct: false },
      { text: '296', correct: false },
    ],
  },
];

button.addEventListener('click', () => {
  quizInfo.style.display = 'none';
  button.style.display = 'none';
  quiz.style.display = 'block';
  renderNextQuestion(currentQuestion);
});
const clearQuestion = () => {
  quiz_question.textContent = '';
  answers_container.innerHTML = '';
};
const renderNextQuestion = i => {
  question_number.textContent = `Question ${i + 1}/12`;
  image.src = `img/${i}.jpg`;
  quiz_question.textContent = questions[i].question;

  //!!!!!
  questions[i].answers.forEach(answer => {
    const answer_text = document.createElement('p');
    answer_text.classList.add('answers__container__answer');
    answer_text.textContent = answer.text;
    if (answer.correct) {
      answer_text.dataset.correct = answer.correct;
    }
    answers_container.append(answer_text);
  });
  //!!!!!
  currentQuestion++;
  document.querySelectorAll('.answers__container__answer').forEach(answer =>
    answer.addEventListener('click', e => {
      if (e.target.dataset.correct) correctAnswers++;
      clearQuestion();
      if (currentQuestion < questions.length)
        renderNextQuestion(currentQuestion);
      if (
        document.querySelector('.answers__container').childElementCount === 0
      ) {
        question_number.style.display = 'none';
        image.src = 'img/end.png';
        image.style.height = '50vh';
        // image.style.width = 'auto';
        quiz_question.textContent = `Correct answers: ${correctAnswers}`;
        correctAnswers <= 7
          ? (resultDescription.textContent =
              "That wasn't very Hogwarts of you...Anything from the trolley, dear? Yep, a well-needed weekend binge-watch please. Time to brush up on your knowledge!")
          : (resultDescription.textContent =
              "You're a wizard, Harry! Butterbeer's on you, because you're actually pretty clued up. Snape would be proud.");
      }
    })
  );
};
*,
::before,
::after {
  margin: 0;
  padding: 0;
  box-sizing: inherit;
}
html {
  box-sizing: border-box;
  font-size: 62.5%;
}
body {
  font-family: 'Amatic SC', cursive;
  color: rgb(0, 0, 0);
  color: rgb(48, 7, 19);
  background: linear-gradient(
      rgba(249, 228, 148, 0.5),
      rgba(249, 228, 148, 0.5)
    ),
    url(img/background.jpg) center/cover fixed no-repeat;
}
.main {
  margin: 2rem 0 0 2rem;
}

img {
  height: 40vh;
  margin: 0.4rem 0 1rem 0;
}
.quiz_info__img {
  height: 45vh;
  opacity: 0.9;
  margin: 1.5rem 0;
}

h1 {
  font-size: 2.3rem;
}

h2 {
  font-size: 2rem;
}

h3 {
  font-size: 1.4rem;
  color: #4c516a;
  margin-top: 0.8rem;
}
.quiz_info {
  width: 60rem;
  font-size: 1.7rem;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
.quiz_info__description {
  margin-bottom: 1rem;
  font-weight: 700;
}
.quiz_info__btn {
  width: 80px;
  padding: 0.6rem;
  background-color: rgb(215, 241, 109);
  border: 1px solid rgb(0, 0, 0);
  border-radius: 3px;
  cursor: pointer;
  font-family: inherit;
  font-size: 1.7rem;
  font-weight: 700;
}
.quiz_info__btn:hover {
  background-color: rgb(255, 255, 240);
}

.quiz {
  display: none;
}
.answers__container {
  display: inline-block;
}
.answers__container__answer {
  padding: 1rem 8rem 1rem 1rem;
  background-color: rgba(240, 248, 255, 0.7);
  border: 1px solid rgb(0, 0, 0);
  cursor: pointer;
  font-size: 18px;
}
.answers__container__answer:hover {
  background-color: rgb(240, 248, 255);
}
.quiz__results-description {
  font-size: 30px;
  width: 70vw;
  color: ivory;
  font-weight: 700;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <script type="module" defer src="script.js"></script>
    <!-- <link rel="preconnect" href="https://fonts.gstatic.com" />
    <link
      href="https://fonts.googleapis.com/css2?family=Amatic+SC:wght@400;700&display=swap"
      rel="stylesheet"
    /> -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@500;700&display=swap" rel="stylesheet"> 
    <link rel="stylesheet" href="styles.css" />
    <script defer src="script.js"></script>
    <title>Harry Potter Quiz</title>
  </head>
  <body>
    <main>
      <div class="container">
        <div class="main">
          <h1>
            QUIZ: How well do you actually remember all 8 Harry Potter films?
          </h1>
          <div class="quiz_info">
            <img
              src="img/start.jpg"
              alt="Harry Potter books"
              class="quiz_info__img"
            />
            <p class="quiz_info__description">
              Were you paying attention during the Harry Potter saga? It's time
              to put your knowledge to the test, as only a real fan can score
              100% in this quiz...
            </p>
            
          </div>
          <button class="quiz_info__btn">Start</button>
          <div class="quiz">
            <h3></h3>
            <img
              src="img/0.jpg"
              alt="Picture from Harry Potter"
              class="quiz__img"
            />
            <h2></h2>
            <div class="answers__container"></div>
            <p class="quiz__results-description"></p>
          </div>
        </div>
      </div>
    </main>
  </body>
</html>

标签: javascript

解决方案


推荐阅读