首页 > 解决方案 > 在我的 HTML 文档中,当我尝试注销输入值时,它是未定义的。为什么?

问题描述

我一直在尝试做一个简单的表单验证js项目,我的第一个逻辑语句本身就有错误。当我试图注销我的输入值时,它说它是未定义的:

<!--skipped css-->
<html>
  <head>
   <title>
    Form validation
   </title>
  </head>
  <body>
   <div class="transparent">
        <div class="form">
            <h1 class="login"> Login </h1>
            <form>
                <label for="name" class="LName">Name</label> 
                <input class="name" id="name" name="name" placeholder="Enter your username"><br>
                <label for="email" class="LEmail">E-mail</label> 
                <input class="email" id="email" name="email" placeholder="Enter your E-mail">   <br>
                <label for="password" class="LPassword">Password</label> 
                <input type="password" class="password" id="password" name="password" placeholder="Enter your password"><br>
            </form> <br>
            <button class="btn"> Login </button>
            <br> <br>
            <span> OR </span><br> <hr>
            <button class="gbtn"> <i class="fab fa-google"></i> Sign in with Google </button>
        </div>
    </div>
    <script>
        var name = document.getElementById('name');
        var email = document.querySelector('.email');
        var password = document.querySelector('.password');
        var btn = document.getElementsByClassName('btn')[0];

        btn.onclick = empty;

        function empty() {
            name = document.getElementById('name');
            console.log(name.value);
            if(name.value == "") {
                name.classList.add('errInp');
            }
    }
    </script>
  </body>
</html>

我相信我已经分配了所有变量,并且我也尝试将其更改为 innerText,只是为了得到另一个未定义的变量。有人可以帮我吗?

标签: javascripthtmlcss

解决方案


我相信您选择“名称”作为变量名是问题所在!通过var name在全局范围内使用分配变量,您将与window.name. 通常,您使用window.name='some name'(字符串)设置窗口的名称。在您尝试为其分配 HTML 元素的情况下,JS 在后台调用.toString(),因此窗口名称实际上是"[object HTMLInputElement]",它没有value属性。

您可以通过将变量名称更改为其他名称来解决它,或者var name =完全摆脱第一个并在内部empty使用const name = document.getElementById('name');而不是name =....


推荐阅读