javascript - 在我的 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,只是为了得到另一个未定义的变量。有人可以帮我吗?
解决方案
我相信您选择“名称”作为变量名是问题所在!通过var name
在全局范围内使用分配变量,您将与window.name
. 通常,您使用window.name='some name'
(字符串)设置窗口的名称。在您尝试为其分配 HTML 元素的情况下,JS 在后台调用.toString()
,因此窗口名称实际上是"[object HTMLInputElement]"
,它没有value
属性。
您可以通过将变量名称更改为其他名称来解决它,或者var name =
完全摆脱第一个并在内部empty
使用const name = document.getElementById('name');
而不是name =...
.
推荐阅读
- reactjs - 如何知道我是否应该将 redux 用于我的应用程序或任何其他替代方案?
- apache-spark - Pyspark 枢轴保留其余列
- vba - VBA动态计数函数
- pyspark - pyspark 将大熊猫数据帧更改为 pyspark 数据帧并写入 s3 出错
- javascript - 如何在Java中保持PNG文件结构
- perl - 在 perl 中尝试::Tiny 和 $SIG{__DIE__}?
- c# - 将默认会话提供程序设置为环境变量
- javascript - 在 __webpack_require__ 中的 NextJS 中构建错误
- r - 如何在R编程中找到数据框列的子组内的平均值?
- python - 从烧瓶路由运行服务器