开发者问题收集

为什么我的 javascript 测验的所有答案都是错误的?

2020-08-04
131

无论我选择哪个答案,我的答案总是错误的。我不确定问题出在哪里,我认为这是因为我在每个按钮上都有一个事件监听器来检查答案。

这是我获取元素的代码

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个回答

if( correct == answerA ){ 将字符串 ( correct ) 与答案 (`answerA`) 的 HTML 元素 进行比较,而不是其文本。

如果您想继续使用 answerA ( answerB 等) 进行此比较,则:

假设您使用 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){
T.J. Crowder
2020-08-04

我建议如下:

  1. 了解您的选择 a、b、c、d 等...
  2. 向每个 HTML 选项添加数据属性以便快速查找
  3. 向每个元素添加事件侦听器;预先
  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>
Mr. Polywhirl
2020-08-04

当您执行 if( correct == answerA ) 时,您正在比较 HTML 元素

var answerA = document.getElementById("answerA")

与字符串

var correct = randomQ.correctAnswer;

这不是有效的比较,但有多种方法可以实现您的目标:使用元素的 textContent 比较字符串 var answerA = document.getElementById("answerA").textContent ,使用元素的 id var answer = answer.target.id.split("answer")[1] 或使用数据属性,如@T.J. Crowder 在他的回答中所建议的。(可能还有更多..)

nip
2020-08-04