使用JavaScript在HTML中构建一个简单的测验

时间:2018-05-04 18:04:51

标签: javascript html

我是HTML和JavaScript的新手,我正在尝试编写函数解决方案,它将返回一个整数分数,用于验证用户选择的复选框的数量是否正确。已经定义了函数 should_be_checked(question_index,choice_index),如果答案正确则返回true,否则返回false。我想在我的解决方案函数中使用函数should_be_checked来评估分数。如何从HTML表单中获取数组中的输入值,然后使用数组值根据should_be_checked函数中的正确值生成分数。 例如: 如果我做了should_be_checked(2,2),它将返回true,因为它是正确的答案。 question_index和choice_index是作为参数传递给should_be_checked函数的值。一旦用户选中复选框,就会在按钮单击时调用solution()函数。



function solution() {
  var score = 0;
  $("input[type=checkbox]").each(checkbox => {
      let args = checkbox.attr("id").split("-"); // Split at the dashes to get an array containing ["choice", "1", "2"]
      args.shift() // Remove the first element that says "choice"
      if (checkbox.prop("checked") !== should_be_checked(...args)) {
        score = score + 1; // Increment the score
      });
    return score;
  }

<form>
  <fieldset id="question-1">
    <legend>Easy question</legend>
    <input type="checkbox" id="choice-1-1" checked>Incorrect answer</input>
  </fieldset>
  <fieldset id="question-2">
    <legend>Another sample question</legend>
    <input type="checkbox" id="choice-2-1">Sample incorrect answer</input><br>
    <input type="checkbox" id="choice-2-2" checked="checked">Sample correct answer</input>
  </fieldset>
</form>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

如果您遍历每个复选框,您可以检查是否应使用您的功能检查它们

let allQuestionsCorrect = true;
$("input[type=checkbox]").each(checkbox => {
  let args = checkbox.attr("id").split("-"); // Split at the dashes to get an array containing ["choice", "1", "2"]
  args.shift() // Remove the first element that says "choice"
  if(checkbox.prop("checked") !== should_be_checked(...args)) {
    allQuestionsCorrect = false; // If it shouldn't be checked and it is or should be checked and it isn't, the questions are not all correct
  }
});
return allQuestionsCorrect

然后,如果他们的checked属性不是它应该返回false