我无法清除表单

I'm Unable to Clear the Form

本文关键字:表单 清除      更新时间:2023-09-26
<!DOCTYPE html>
<html>
<head>
    <title>Onreset-3</title>
</head>
<body>
    <form>
        Username: <input type="text" class="abc"><br><br>
        Password: <input type="password" class="abc"><br><br>
    </form>
    <input type="button" onclick="reset()" value="Clear">
    <script>
        function reset()
        {
            var a = document.getElementsByClassName('abc');
            a.value = "";
        }
    </script>
</body>
</html>

我无法清除上述表格中的用户名和密码。我一直在尝试使用 id 但没有用

本机重置更好且完美运行

    <form>
        Username: <input type="text" class="abc"><br><br>
        Password: <input type="password" class="abc"><br><br>
    </form>
    <input type="button" onclick="reset()" value="Clear">
    <script>
        function reset()
        {
            document.getElementsByTagName("form")[0].reset();
        }
    </script>

在你的代码中:

document.getElementsByClassName('abc');

返回所有子元素的类似数组的对象,这些子元素具有所有 给定的类名。

MDN: getElementsByClassName

结果值为HTMLCollection

在这种情况下,我们可以循环访问集合。

使用 Javascript 通过使用 HTMLCollection

<!DOCTYPE html>
<html>
<head>
  <title>Onreset-3</title>
</head>
<body>
  <form>
    Username:
    <input type="text" class="abc">
    <br>
    <br>Password:
    <input type="password" class="abc">
    <br>
    <br>
  </form>
  <input type="button" onclick="reset()" value="Clear">
  <script>
    function reset() {
      var a = document.getElementsByClassName('abc');
      // a = HTMLCollection
      console.log(a);
      // You can iterate over HTMLCollection.
      for (var i = 0; i < a.length; i++) {
        // You can set the value in every item in the HTMLCollection.
        a[i].value = "";
      }
    }
  </script>
</body>
</html>

没有Javascript

但是,您的表单可以完美地与重置按钮一起使用。<input type="reset" value="Clear">必须位于表单标记内。

像这样:

<!DOCTYPE html>
<html>
<head>
  <title>Onreset-3</title>
</head>
<body>
  <form>
    Username:
    <input type="text" class="abc">
    <br>
    <br>Password:
    <input type="password" class="abc">
    <br>
    <br>
    <input type="reset" value="Clear">
  </form>
</body>
</html>

附加信息:

HTMLFormElement.reset() The HTMLFormElement.reset()方法恢复表单元素的默认值。此方法执行相同的操作 就像单击表单的重置按钮一样。

如果窗体控件(如重置按钮(的名称或 ID 为 reset 它将屏蔽窗体的重置方法。它不会重置其他 输入中的属性,例如禁用。

用法:

document.getElementById("myform").reset();

HTMLFormElement.reset()