javascript - 如何防止用户在我的测验中选择多个答案?

标签 javascript jquery html css

我遇到的问题是,一旦用户选择一个答案,然后点击“提交答案”并收到他们的反馈,他们就可以继续点击并选择其他答案,然后再继续下一个问题。一旦用户提交了一个答案,我该如何阻止他们这样做?

let score = 0;
let currentQuestion = 0;
let questions = [{
    title: "At what age was Harry Potter when he received his Hogwarts letter?",
    answers: ['7', '10', '11', '13'],
    correct: 1
  },
  {
    title: "Which is not a Hogwarts house?",
    answers: ['Dunder Mifflin', 'Ravenclaw', 'Slytherin', 'Gryffindor'],
    correct: 0
  },
  {
    title: "Who teaches Transfiguration at Hogwarts?",
    answers: ['Rubeus Hagrid', 'Albus Dumbledore', 'Severus Snape', 'Minerva McGonnagle'],
    correct: 3
  },
  {
    title: "Where is Hogwarts School for Witchcraft and Wizardry located?",
    answers: ['France', 'USA', 'UK', 'New Zealand'],
    correct: 2
  },
  {
    title: "What form does Harry Potter's patronus charm take?",
    answers: ['Stag', 'Eagle', 'Bear', 'Dragon'],
    correct: 0
  },
  {
    title: "What type of animal is Harry's pet?",
    answers: ['Dog', 'Owl', 'Cat', 'Snake'],
    correct: 1
  },
  {
    title: "Who is not a member of the Order of the Phoenix?",
    answers: ['Remus Lupin', 'Siruis Black', 'Lucious Malfoy', 'Severus Snape'],
    correct: 2
  },
  {
    title: "What is not a piece of the Deathly Hallows?",
    answers: ['Elder Wand', 'Cloak of Invisibility', 'Resurrection Stone', 'Sword of Gryffindor'],
    correct: 3
  },
  {
    title: "In which house is Harry sorted into after arriving at Hogwarts?",
    answers: ['Slytherin', 'Ravenclaw', 'Gryffindor', 'Hufflepuff'],
    correct: 2
  },
  {
    title: "What prevented Voldemort from being able to kill Harry Potter when he was a baby?",
    answers: ['Love', 'Anger', 'Friendship', 'Joy'],
    correct: 0
  },
];



$(document).ready(function() {

  $('.start a').click(function(e) {
    e.preventDefault();
    $('.start').hide();
    $('.quiz').show();
    showQuestion();
  });

  $('.quiz').on('click', 'button', function() {
    $('.selected').removeClass('selected');
    $(this).addClass('selected');
  });

  $('.quiz a.submit').click(function(e) {
    e.preventDefault();
    if ($('button.selected').length) {
      let guess = parseInt($('button.selected').attr('id'));
      checkAnswer(guess);
    } else {
      alert('Please select an answer');
    }
  });

  $('.summary a').click(function(e) {
    e.preventDefault();
    restartQuiz();
  });

});

function showQuestion() {
  let question = questions[currentQuestion];
  $('.quiz h2').text(question.title);
  $('.quiz div:nth-child(2)').html('');
  for (var i = 0; i < question.answers.length; i++) {
    $('.quiz div:nth-child(2)').append(`<button id="${i}">${question.answers[i]}</button>`);
  }
  showProgress();
}

function showIncorrectQuestion(guess) {
  let question = questions[currentQuestion];
  $('.quiz h2').text(question.title);
  $('.quiz div:nth-child(2)').html('');
  for (var i = 0; i < question.answers.length; i++) {
    let cls = i === question.correct ? "selected" : guess === i ? "wrong" : ""
    $('.quiz div:nth-child(2)').append(`<button id="${i}" class="${cls}">${question.answers[i]}</button>`);
  }
  showProgress();
}

function checkAnswer(guess) {
  let question = questions[currentQuestion];
  if (question.correct === guess) {
    if (!question.alreadyAnswered) {
      score++;
    }
    showIsCorrect(true);

  } else {
    showIsCorrect(false);
    showIncorrectQuestion(guess);
  }
  question.alreadyAnswered = true;
}

function showSummary() {
  $('.quiz').hide();
  $('.summary').show();
  $('.summary p').text("Thank you for taking the quiz! Here's how you scored. You answered " + score + " out of " + questions.length + " correctly! Care to try again?")
}

function restartQuiz() {
  questions.forEach(q => q.alreadyAnswered = false);

  $('.summary').hide();
  $('.quiz').show();
  score = 0;
  currentQuestion = 0;
  showQuestion();
}

function showProgress() {
  $('#currentQuestion').html(currentQuestion + " out of " + questions.length);
}

function showIsCorrect(isCorrect) {
  var result = "Wrong";
  if (isCorrect) {
    result = "Correct";
  }
  $('#isCorrect').html(result);
  $('.navigate').show();
  $('.submit').hide();
}
$('.navigate').click(function() {
  currentQuestion++;
  if (currentQuestion >= questions.length) {
    showSummary();
  } else {
    showQuestion();
  }

  $('.navigate').hide();
  $('.submit').show();
  $('#isCorrect').html('');
})
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  text-decoration: none;
  text-align: center;
  background-color: #837F73;
}

h1 {
  font-family: 'Poor Story', cursive;
  background-color: #950002;
  padding: 60px;
  color: #FFAB0D;
  text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}

h2 {
  font-family: 'Poor Story', cursive;
  font-size: 30px;
  padding: 60px;
  background-color: #950002;
  color: #FFAB0D;
  text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}

p {
  font-family: 'Poor Story', cursive;
  background-color: #FFAB0D;
  font-size: 20px;
  font-weight: bold;
}

a {
  border: 1px solid #222F5B;
  padding: 10px;
  background-color: #222F5B;
  color: silver;
  border-radius: 5px;
  margin-top: 50px;
  display: inline-block;
}

a:hover {
  border: 1px solid #000000;
  background-color: #000000;
  color: #FCBF2B;
}

.quiz button {
  cursor: pointer;
  border: 1px solid;
  display: inline-block;
  width: 200px;
  margin: 10px;
  font-family: 'Poor Story', cursive;
  font-size: 26px;
}

#currentQuestion {
  color: #000000;
  font-size: 18px;
  font-family: 'Poor Story', cursive;
  margin-top: 10px;
}

#isCorrect {
  color: white;
  font-family: 'Poor Story', cursive;
  font-weight: bold;
  font-size: 18px;
}

.quiz,
.summary {
  display: none;
}

.quiz ul {
  margin-top: 20px;
  list-style: none;
  padding: 0;
}

.selected {
  background-color: #398C3F;
}

.wrong {
  background-color: red;
}
<html lang="en">

  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="https://fonts.googleapis.com/css?family=Poor+Story" rel="stylesheet">
    <link href="style.css" rel="stylesheet" type="text/css" />
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Harry Potter Quiz</title>
  </head>

  <body>

  <header role="banner">
    <div class="start">
  <h1>How Well Do You Know Harry Potter?</h1>
  <a href="#">Start Quiz</a>
</div>
  </header>


<main role="main">
<div class="quiz">
  <h2>Question Title</h2>
  <div>
    <button>Choice</button>
    <button>Choice</button>
    <button>Choice</button>
    <button>Choice</button>
  </div>
  <a class="submit" href="#">Submit Answer</a>
  <a class="navigate" style="display:none;" href="#">Next Question</a>
  <div id="currentQuestion"></div>
  <footer role="contentinfo">
  <div id="isCorrect"></div>
  </footer>
</div>
</main>


<div class="summary">
  <h2>Results</h2>
  <p>Thank you for taking the quiz! Here's how you scored. You answered x out of y correctly! Care to try again?</p>
  <a href="#">Retake Quiz</a>
</div>

    <script src="index.js"></script>

    <!--jQuery script when using JSBin-->
    <!--<script src="https://code.jquery.com/jquery-3.1.0.js"></script>-->

  </body>

</html>

最佳答案

我已经声明了一个名为 buttonClickable 的变量,并将它用作每次单击按钮时的标志。当用户提交答案时,buttonclickable 变为 false,而当您呈现新问题时,buttonclickable 变为 true。

let score = 0;
let currentQuestion = 0;

let buttonClickable = true;

let questions = [{
    title: "At what age was Harry Potter when he received his Hogwarts letter?",
    answers: ['7', '10', '11', '13'],
    correct: 1
  },
  {
    title: "Which is not a Hogwarts house?",
    answers: ['Dunder Mifflin', 'Ravenclaw', 'Slytherin', 'Gryffindor'],
    correct: 0
  },
  {
    title: "Who teaches Transfiguration at Hogwarts?",
    answers: ['Rubeus Hagrid', 'Albus Dumbledore', 'Severus Snape', 'Minerva McGonnagle'],
    correct: 3
  },
  {
    title: "Where is Hogwarts School for Witchcraft and Wizardry located?",
    answers: ['France', 'USA', 'UK', 'New Zealand'],
    correct: 2
  },
  {
    title: "What form does Harry Potter's patronus charm take?",
    answers: ['Stag', 'Eagle', 'Bear', 'Dragon'],
    correct: 0
  },
  {
    title: "What type of animal is Harry's pet?",
    answers: ['Dog', 'Owl', 'Cat', 'Snake'],
    correct: 1
  },
  {
    title: "Who is not a member of the Order of the Phoenix?",
    answers: ['Remus Lupin', 'Siruis Black', 'Lucious Malfoy', 'Severus Snape'],
    correct: 2
  },
  {
    title: "What is not a piece of the Deathly Hallows?",
    answers: ['Elder Wand', 'Cloak of Invisibility', 'Resurrection Stone', 'Sword of Gryffindor'],
    correct: 3
  },
  {
    title: "In which house is Harry sorted into after arriving at Hogwarts?",
    answers: ['Slytherin', 'Ravenclaw', 'Gryffindor', 'Hufflepuff'],
    correct: 2
  },
  {
    title: "What prevented Voldemort from being able to kill Harry Potter when he was a baby?",
    answers: ['Love', 'Anger', 'Friendship', 'Joy'],
    correct: 0
  },
];



$(document).ready(function() {

  $('.start a').click(function(e) {
    e.preventDefault();
    $('.start').hide();
    $('.quiz').show();
    showQuestion();
  });

  $('.quiz').on('click', 'button', function() {
    if(!buttonClickable) return;
    $('.selected').removeClass('selected');
    $(this).addClass('selected');
  });

  $('.quiz a.submit').click(function(e) {
    e.preventDefault();
    if ($('button.selected').length) {
      let guess = parseInt($('button.selected').attr('id'));
      checkAnswer(guess);
    } else {
      alert('Please select an answer');
    }
  });

  $('.summary a').click(function(e) {
    e.preventDefault();
    restartQuiz();
  });

});

function showQuestion() {
  buttonClickable = true;
  let question = questions[currentQuestion];
  $('.quiz h2').text(question.title);
  $('.quiz div:nth-child(2)').html('');
  for (var i = 0; i < question.answers.length; i++) {
    $('.quiz div:nth-child(2)').append(`<button id="${i}">${question.answers[i]}</button>`);
  }
  showProgress();
}

function showIncorrectQuestion(guess) {
  let question = questions[currentQuestion];
  $('.quiz h2').text(question.title);
  $('.quiz div:nth-child(2)').html('');
  for (var i = 0; i < question.answers.length; i++) {
    let cls = i === question.correct ? "selected" : guess === i ? "wrong" : ""
    $('.quiz div:nth-child(2)').append(`<button id="${i}" class="${cls}">${question.answers[i]}</button>`);
  }
  showProgress();
}

function checkAnswer(guess) {
  buttonClickable = false;
  let question = questions[currentQuestion];
  if (question.correct === guess) {
    if (!question.alreadyAnswered) {
      score++;
    }
    showIsCorrect(true);

  } else {
    showIsCorrect(false);
    showIncorrectQuestion(guess);
  }
  question.alreadyAnswered = true;
}

function showSummary() {
  $('.quiz').hide();
  $('.summary').show();
  $('.summary p').text("Thank you for taking the quiz! Here's how you scored. You answered " + score + " out of " + questions.length + " correctly! Care to try again?")
}

function restartQuiz() {
  questions.forEach(q => q.alreadyAnswered = false);

  $('.summary').hide();
  $('.quiz').show();
  score = 0;
  currentQuestion = 0;
  showQuestion();
}

function showProgress() {
  $('#currentQuestion').html(currentQuestion + " out of " + questions.length);
}

function showIsCorrect(isCorrect) {
  var result = "Wrong";
  if (isCorrect) {
    result = "Correct";
  }
  $('#isCorrect').html(result);
  $('.navigate').show();
  $('.submit').hide();
}
$('.navigate').click(function() {
  currentQuestion++;
  if (currentQuestion >= questions.length) {
    showSummary();
  } else {
    showQuestion();
  }

  $('.navigate').hide();
  $('.submit').show();
  $('#isCorrect').html('');
})
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  text-decoration: none;
  text-align: center;
  background-color: #837F73;
}

h1 {
  font-family: 'Poor Story', cursive;
  background-color: #950002;
  padding: 60px;
  color: #FFAB0D;
  text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}

h2 {
  font-family: 'Poor Story', cursive;
  font-size: 30px;
  padding: 60px;
  background-color: #950002;
  color: #FFAB0D;
  text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}

p {
  font-family: 'Poor Story', cursive;
  background-color: #FFAB0D;
  font-size: 20px;
  font-weight: bold;
}

a {
  border: 1px solid #222F5B;
  padding: 10px;
  background-color: #222F5B;
  color: silver;
  border-radius: 5px;
  margin-top: 50px;
  display: inline-block;
}

a:hover {
  border: 1px solid #000000;
  background-color: #000000;
  color: #FCBF2B;
}

.quiz button {
  cursor: pointer;
  border: 1px solid;
  display: inline-block;
  width: 200px;
  margin: 10px;
  font-family: 'Poor Story', cursive;
  font-size: 26px;
}

#currentQuestion {
  color: #000000;
  font-size: 18px;
  font-family: 'Poor Story', cursive;
  margin-top: 10px;
}

#isCorrect {
  color: white;
  font-family: 'Poor Story', cursive;
  font-weight: bold;
  font-size: 18px;
}

.quiz,
.summary {
  display: none;
}

.quiz ul {
  margin-top: 20px;
  list-style: none;
  padding: 0;
}

.selected {
  background-color: #398C3F;
}

.wrong {
  background-color: red;
}
<html lang="en">

  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="https://fonts.googleapis.com/css?family=Poor+Story" rel="stylesheet">
    <link href="style.css" rel="stylesheet" type="text/css" />
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Harry Potter Quiz</title>
  </head>

  <body>

  <header role="banner">
    <div class="start">
  <h1>How Well Do You Know Harry Potter?</h1>
  <a href="#">Start Quiz</a>
</div>
  </header>


<main role="main">
<div class="quiz">
  <h2>Question Title</h2>
  <div>
    <button>Choice</button>
    <button>Choice</button>
    <button>Choice</button>
    <button>Choice</button>
  </div>
  <a class="submit" href="#">Submit Answer</a>
  <a class="navigate" style="display:none;" href="#">Next Question</a>
  <div id="currentQuestion"></div>
  <footer role="contentinfo">
  <div id="isCorrect"></div>
  </footer>
</div>
</main>


<div class="summary">
  <h2>Results</h2>
  <p>Thank you for taking the quiz! Here's how you scored. You answered x out of y correctly! Care to try again?</p>
  <a href="#">Retake Quiz</a>
</div>

    <script src="index.js"></script>

    <!--jQuery script when using JSBin-->
    <!--<script src="https://code.jquery.com/jquery-3.1.0.js"></script>-->

  </body>

</html>

关于javascript - 如何防止用户在我的测验中选择多个答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53441712/

相关文章:

javascript - 无法读取路由参数中未定义的属性 'name'

javascript - 从选项卡式框中滚动到下一个和上一个选项卡

javascript - 如何获取从范围 slider 派生的值的总和

html - 创建跨浏览器的背景渐变

javascript - 基于条件的 VueJS HTML 元素类型

javascript - 发出 Axios GET 请求时无限循环 - 循环不会关闭

javascript - 使用调试器时,如何强制 IE9 为 "see"最新的 javascript?

javascript - 脚本加载发生在 JSDOM 中的窗口加载之后

javascript - 使用 jQuery 从多个表中删除行

html - HighCharts Angular - 来自 API 的数据未显示在图表中