JavaScript登录表单document.getElementById未检测到值

问题描述 投票:1回答:3

任何人都可以告诉我为什么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”,我不知道这意味着什么,除了某些原因它没有我想要分配给它的值。

-谢谢

javascript html html-form login-script
3个回答
2
投票

函数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>

0
投票

改变这些行

   if(document.getElementById("password") == password){
   console.log(document.getElementById("password"));

这些线

   if(document.getElementById("password").value == password){
   console.log(document.getElementById("password").value);

而鲍勃是你的叔叔。


0
投票

你的实现没问题,但你犯了一个小错误。 document返回具有多个键的对象。在这些键中,'value'键包含输入字段的值。

document.getElementById("password").value

将返回您想要的值。

注意:您可以访问此对象的所有属性。例如

document.getElementById("password").placeholder 

将从输入字段返回提示

© www.soinside.com 2019 - 2024. All rights reserved.