任何人都可以告诉我为什么document.getElementById没有检测到下面代码中输入的密码:
function myFunction() {
let email = "[email protected]";
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 = "[email protected]";
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>
改变这些行
if(document.getElementById("password") == password){
console.log(document.getElementById("password"));
这些线
if(document.getElementById("password").value == password){
console.log(document.getElementById("password").value);
而鲍勃是你的叔叔。
你的实现没问题,但你犯了一个小错误。 document返回具有多个键的对象。在这些键中,'value'键包含输入字段的值。
document.getElementById("password").value
将返回您想要的值。
注意:您可以访问此对象的所有属性。例如
document.getElementById("password").placeholder
将从输入字段返回提示