提问者:小点点

DOM测验会给出错误答案


我正在学习DOM,希望创建一个简单的JavaScript with Html测验(用于练习)。现在我遇到的问题是,当我点击提交时,所有的答案都是对的,而不是一个是对的,三个是错的。我认为这是我的html和我将ID分配给不同标签的方式的问题,但我不能弄清楚我做错了什么。

代码

<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="quiz.css">

  </head>

  <body>

<div class="QuestionOne">
  <form id="quizForm">
<h1> What is your favorite color?</h1>

<input type="radio" id="red" name="color" value="red">
<label for="red">Red</label><br>
<p></p>
<input type="radio" id="blue" name="color" value="blue">
<label for="blue">Blue</label><br>
<p></p>
<input type="radio" id="green" name="color" value="green">
<label for="green">Green</label>
<p></p>
<input type="submit" id="submit" name="color" value="Submit"><br>
</form>
</div>





<script src="quiz.js">

</script>
  </body>
</html>

quizForm.addEventListener("submit",function(event) {
  event.preventDefault();
  var grabAnswer = document.getElementById('red')
  console.log(grabAnswer.id);


  if (grabAnswer.id == 'red') {
    console.log('correct!');
  }else{
    console.log('wrong');
  }


})

多谢了。


共1个答案

匿名用户

问题是,您总是在grapAnswer中使用红色,但您必须使用var grabAnswer=document.QuerySelector('input[name=“color”]:checked');

演示

null

var quizForm = document.getElementById("quizForm")

quizForm.addEventListener("submit", function(event) {
  event.preventDefault();
  var grabAnswer = document.querySelector('input[name="color"]:checked');
  console.log(grabAnswer.id);


  if (grabAnswer.id == 'red') {
    console.log('correct!');
  } else {
    console.log('wrong');
  }


})
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>
  <link rel="stylesheet" href="quiz.css">

</head>

<body>

  <div class="QuestionOne">
    <form id="quizForm">
      <h1> What is your favorite color?</h1>

      <input type="radio" id="red" name="color" value="red">
      <label for="red">Red</label><br>
      <p></p>
      <input type="radio" id="blue" name="color" value="blue">
      <label for="blue">Blue</label><br>
      <p></p>
      <input type="radio" id="green" name="color" value="green">
      <label for="green">Green</label>
      <p></p>
      <input type="submit" id="submit" name="color" value="Submit"><br>
    </form>
  </div>





  <script src="quiz.js">
  </script>
</body>

</html>