如何在没有服务器的本地驱动器上使用 JavaScript/AJAX 验证输入值

how to validate input values using javascript/ajax on local drive without server

本文关键字:JavaScript AJAX 输入 验证 驱动器 服务器      更新时间:2023-09-26

我将为将在本地计算机上运行HTML格式的学生分享一堂关于HTML格式的课程。我希望学习者能够检查答案,他们将这些答案写入输入中。一旦他们在本地运行它,答案表的地址栏如下所示:

file:///D:/XAMPP/htdocs/ielts/modules/reading/answers_sheet.html

输入区域如下所示:

<td class="reading">
    <input type="text" name="01" class="txt " maxlength="50" value="">
</td>
<td class="reading">
    <input type="text" name="02" class="txt " maxlength="50" value="">
</td>
...
........
<input type="button" class="button" name="check" id="check" value="Check your answers" onclick="submit();">

在他们输入他们的回答并单击"检查您的答案"按钮后,它应该看起来像这样:

<td class="reading">
    <img src="/images/correct.gif" style="float:right;">
    <input type="text" name="01" class="txt " maxlength="50" value="premises">
</td>
<td class="reading">
    <img src="/images/wrong.gif" style="float:right;">
    <span class="correct_anwser">(premises)</span>
</td>

你能帮我创建一个脚本来检查答案并显示它们是否正确吗?我将不胜感激有关此主题的任何反馈。

您可以将以下内容添加到 HTML 文档的底部:

<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
    // List your answers to match the "name" attribute of the input
    // with the key ("01", "02", etc) of this object
    var correctAnswers = {
        "01": "alpha",
        "02": "beta",
        "03": "delta"
    }
    // Click on the check button
    $("#check").on("click", function() {
      // Clear results of previous submission
      $(".img-box").empty();
      // Loop through each element that has the "reading" class
      $(".reading").each(function(index) {
          // Find the input contained in each reading element
          var input = $(this).find('input').first();
          // Get the value for the "name" attribute
          var reading = $(input).attr("name");
          // Get the input value
          var value = $(input).val();
          // Check if the value matches the value of the element in the
          // correctAnswers object
          if (value == correctAnswers[reading]) {
              // Insert the "correct" image if it does
              $(this).prepend('<div class="img-box"><img src="/images/correct.gif" style="float:right;"></div>');
          } else {
              // Insert the "incorrect" image if it does not
              $(this).prepend('<div class="img-box"><img src="/images/wrong.gif" style="float:right;"></div>');
          }
      });
    });
</script>

你应该能够看到它在Plunker上工作