首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用JavaScript在HTML中构建一个简单的测试

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

Stack Overflow用户
提问于 2018-05-04 18:04:50
回答 1查看 880关注 0票数 0

我是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函数的值。一旦用户选择复选框,解决方案()函数将在单击按钮上被调用。

代码语言:javascript
复制
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;
  }
代码语言:javascript
复制
<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>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-04 18:14:47

如果循环遍历每个复选框,则可以检查是否应该使用函数检查它们。

代码语言:javascript
复制
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

如果检查的属性不是应该返回的属性,则返回false

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50180783

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档