谁能告诉我为什么 document.getElementById 没有检测到在下面的代码中输入的密码:
function myFunction() {
let email = "name@email.com";
let password = "password";
if (document.getElementById("password") == password) {
Console.console.log("success");
} else {
console.log("Failure");
console.log(password);
console.log(document.getElementById("password"));
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="#">
<label for="Email">Email</label>
<input id="email" type="email">
<label for="password">Password</label>
<input id="password" type="text">
<button onclick="myFunction()">Submit</button>
</form>
</body>
</html>
当我尝试在控制台中记录它的值时,我只得到输入 id="password"type="text"我不确定这意味着什么,除了出于某种原因它没有我想要分配的值
-谢谢
最佳答案
函数document.getElementById
返回一个 DOM 元素对象。该对象具有各种属性,如 .style
, 但要获取为 <input>
输入的文本元素,你想要 .value
属性。
function myFunction() {
let email = "name@email.com";
let password = "password";
if (document.getElementById("password").value == password){
console.log("success");
} else {
console.log("Failure");
console.log(password);
console.log(document.getElementById("password").value);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="#">
<label for="Email">Email</label>
<input id="email" type="email">
<label for="password">Password</label>
<input id="password" type="text">
<button onclick="myFunction()">Submit</button>
</form>
</body>
</html>
关于JavaScript 登录表单 document.getElementById 未检测到值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52130526/