Почему все ответы на мою викторину javascript вернулись неверно? - PullRequest
0 голосов
/ 04 августа 2020

Независимо от того, какой ответ я выберу, мой ответ всегда возвращается как неправильный. Я не уверен, в чем проблема, я думаю, это потому, что у меня есть прослушиватель событий на каждой кнопке, чтобы проверить ответ.

Вот код того, как я получаю свои элементы

var questionLocation = document.getElementById("questionLocation")
var answerA = document.getElementById("answerA")
var answerB = document.getElementById("answerB")
var answerC = document.getElementById("answerC")
var answerD = document.getElementById("answerD")

window.addEventListener("load", function pullRandom() {
  let randomQ = myQuestions[Math.floor(Math.random() * myQuestions.length)];
  console.log(randomQ)

  questionLocation.innerHTML = randomQ.Question;
  answerA.innerHTML = randomQ.answers.a;
  answerB.innerHTML = randomQ.answers.b;
  answerC.innerHTML = randomQ.answers.c;
  answerD.innerHTML = randomQ.answers.d;
  var correct = randomQ.correctAnswer;
  console.log(correct)

Это мои кнопки

<div class="jumbotron" id="jumbotron">
  <div id="questionHolder" style="display: block;">
    <h4 id="questionLocation"></h4>
    <div id="answers">
      <div id="answerA" class="btn btn-dark"></div>
      <div id="answerB" class="btn btn-dark"></div>
      <div id="answerC" class="btn btn-dark"></div>
      <div id="answerD" class="btn btn-dark"></div>
    </div>
  </div>
</div>

Вот образец моего массива вопросов

const myQuestions = [{
    Question: "What alloy is Captain America's sheild made of?",
    answers: {
      a: "Steel",
      b: "Adamantium",
      c: "Vibrainium",
      d: "Uru"
    },
    correctAnswer: "c"
  },
  {
    Question: "What was the code name of the Government project that gave Captain America his powers?",
    answers: {
      a: "Weapon X",
      b: "Super Soldier",
      c: "AIM",
      d: "Hyrda"
    },
    correctAnswer: "b"
  },
  {
    Question: "What was the name of the Virtual Intellegnce designed by Iron man?",
    answers: {
      a: "Jarvis",
      b: "Hal 9000",
      c: "T-800",
      d: "R2-D2"
    },
    correctAnswer: "a"
  },
  {
    Question: "What did Iron man build to power his suits and keep himself alive?",
    answers: {
      a: "Skynet",
      b: "Death Star",
      c: "Gamma Bomb",
      d: "Arc Reactor"
    },
    correctAnswer: "d"
  }
]

И это слушатели событий, которые я должен проверить

answerA.addEventListener("click", function checkAnswers(answer) {
  if (correct == answerA) {
    alert("Correct!")
    score++;
  } else {
    alert("Wrong!")
    console.log(score)
  }
});

answerB.addEventListener("click", function checkAnswers(answer) {
  if (correct == answerB) {
    alert("Correct!")
    score++;
  } else {
    alert("Wrong!")
    console.log(score)
  }
});

answerC.addEventListener("click", function checkAnswers(answer) {
  if (correct == answerC) {
    alert("Correct!")
    score++;
  } else {
    alert("Wrong!")
    console.log(score)
  }
});

answerD.addEventListener("click", function checkAnswers(answer) {
  if (correct == answerD) {
    alert("Correct!")
    score++;
  } else {
    alert("Wrong!")
    console.log(score)
  }
});

Я не совсем уверен, где я ошибаюсь.

Ответы [ 3 ]

1 голос
/ 04 августа 2020

Я рекомендую следующее:

  1. Знайте свой выбор a, b, c, d, et c ...
  2. Добавьте атрибуты данных к каждому HTML выбор для быстрого поиска
  3. Добавить слушателей событий к каждому из элементов; up-front
  4. Получить случайный вопрос
  5. Заполнить textContent каждой «кнопки»
  6. Проверить ответ, сравнив атрибут данных с правильным выбором

Это вводит цикл для динамической настройки содержимого формы вопроса.

Проверить ответ теперь так же просто, как:

e.target.dataset.choice === randomQ.correctAnswer

const myQuestions = getQuestions();
const choices = ['a', 'b', 'c', 'd'];

let score = 0;
let randomQ = null;

const main = () => {
  choices.forEach(x => {
    document.getElementById('answer' + x.toUpperCase())
      .addEventListener('click', checkAnswers)
  });

  prepareQuestion();
};

const prepareQuestion = () => {
  randomQ = retrieveRandomQuestion(myQuestions);
  const questionLocation = document.getElementById("questionLocation");
  questionLocation.innerHTML = randomQ.Question;
  choices.forEach(x => {
    var choice = document.getElementById('answer' + x.toUpperCase());
    choice.textContent = randomQ.answers[x];
  });
}

const checkAnswers = (e) => {
  if (e.target.dataset.choice === randomQ.correctAnswer) {
    alert("Correct!");
    score++;
    prepareQuestion(); // Ask another random question
  } else {
    alert("Wrong!");
    console.log(`Final score: ${score}`);
  }
}

const retrieveRandomQuestion = (questions) =>
  questions[Math.floor(Math.random() * questions.length)];

main();

// Convenience function to retrieve data above...

function getQuestions() {
  return [{
    Question: "What alloy is Captain America's sheild made of?",
    answers: {
      a: "Steel",
      b: "Adamantium",
      c: "Vibrainium",
      d: "Uru"
    },
    correctAnswer: "c"
  }, {
    Question: "What was the code name of the Government project that gave Captain America his powers?",
    answers: {
      a: "Weapon X",
      b: "Super Soldier",
      c: "AIM",
      d: "Hyrda"
    },
    correctAnswer: "b"
  }, {
    Question: "What was the name of the Virtual Intellegnce designed by Iron man?",
    answers: {
      a: "Jarvis",
      b: "Hal 9000",
      c: "T-800",
      d: "R2-D2"
    },
    correctAnswer: "a"
  }, {
    Question: "What did Iron man build to power his suits and keep himself alive?",
    answers: {
      a: "Skynet",
      b: "Death Star",
      c: "Gamma Bomb",
      d: "Arc Reactor"
    },
    correctAnswer: "d"
  }];
}
body {
  background: #112;
}

#questionHolder {
  color: #FFF;
  text-align: center;
}

#answers {
  display: flex;
  flex-wrap: wrap;
}

.btn {
  flex: calc(50% - 2em);
  width: 8em;
  margin: 0.25em 0;
  padding: 0.5em;
  margin: 0.25em;
  text-align: center;
  border: thin solid #557;
}

.btn:hover {
  cursor: pointer;
  font-weight: bold;
}

.btn-dark {
  background: #225;
  color: #FFF;
}

.btn-dark:hover {
  background: #ED0;
  color: #000;
}

.btn-dark:active {
  background: #F70;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css">
<div class="jumbotron" id="jumbotron">
  <div id="questionHolder" style="display: block;">
    <h4 id="questionLocation"></h4>
    <div id="answers">
      <div id="answerA" class="btn btn-dark" data-choice="a"></div>
      <div id="answerB" class="btn btn-dark" data-choice="b"></div>
      <div id="answerC" class="btn btn-dark" data-choice="c"></div>
      <div id="answerD" class="btn btn-dark" data-choice="d"></div>
    </div>
  </div>
</div>
1 голос
/ 04 августа 2020

if( correct == answerA ){ сравнивает строку (correct) с HTML элементом для ответа (`answerA), а не его текста.

Если вы хотите продолжать использовать answerA (answerB, et c.) Для этого сравнения:

Учитывая, что вы устанавливаете ответ с помощью innerHTML, вы можете использовать innerHTML для сравнения:

if( correct == answerA.innerHTML){

но , HTML, которое вы получаете в ответ из браузера, может отличаться от HTML, которое вы указали для него. Если вы хотите вернуть именно тот текст, который вы на нем поместили, вы можете сохранить его в атрибуте. Кроме того, если вы действительно не хотите указывать HTML в ответах, используйте textContent вместо innerHTML:

answerA.textContent = randomQ.answers.a;
answerA.setAttribute("data-answer", randomQ.answers.a);

Затем позже

if( correct == answerA.getAttribute("data-answer")){

Тем не менее, я вообще не думаю, что смогу сравнивать с элементом HTML. Вместо этого я бы сравнил с ответами на вопрос:

if( correct == randomQ.answers.a){
0 голосов
/ 04 августа 2020

Когда вы выполняете if( correct == answerA ), вы сравниваете HTML элемент

var answerA = document.getElementById("answerA")

со строкой

var correct = randomQ.correctAnswer;

Это недопустимое сравнение, но есть несколько способов достижения вашей цели: используйте элемент textContent для сравнения строк var answerA = document.getElementById("answerA").textContent, используйте идентификатор элемента var answer = answer.target.id.split("answer")[1] или используйте атрибуты данных, такие как @TJ Crowder, предложенные в его ответ. (и, наверное, больше ..)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...