我需要帮助在html/javascript中创建密码表单

我需要帮助在html/javascript中创建密码表单,javascript,html,Javascript,Html,我正在尝试创建一个密码字段,但如果有人知道该字段出了什么问题,则该字段不起作用 我的代码(可能是所有的,因为这是我的第二个项目)我将非常感激 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Password</title> <script>

我正在尝试创建一个密码字段,但如果有人知道该字段出了什么问题,则该字段不起作用
我的代码(可能是所有的,因为这是我的第二个项目)我将非常感激

    <!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">

        <title>Password</title>
        <script>
            (function pw_check() {
  var $password;
  $password = document.write(document.getElementById("password"));
  if ($password = "pass") {window.open("alert.html");} 
  else {window.open("pwfail.html");};
  });

        </script>

        <meta name="viewport" content="width=device-width; initial-scale=1.0">
    </head>

    <body>
        <form>
            <input type="password"/>
            <button onclick="pw_check" id="password">submit</button>
        </form>
    </body>
</html>

密码
(功能pw_检查(){
var$密码;
$password=document.write(document.getElementById(“密码”);
如果($password=“pass”){window.open(“alert.html”);}
else{window.open(“pwfail.html”);};
});
提交
添加ID:

您试图通过ID获取元素:
document.getElementById(“密码”)
,而您的输入没有ID

 <input type="password"/>

添加一个ID:

 <input id="password" type="password"/>

删除按钮中的ID-ID必须是唯一的。

两个问题:

  • onclick=“pw_check();”
    ,否则您只是引用函数,而不是实际调用它

  • 你的
    pw\u check()
    函数有各种各样的错误。尝试:

    function pw_check() {
        var pw = document.getElementById('password_input').value;
        if( pw == "pass") location.href = "alert.html";
        else location.href = "pwfail.html";
    }
    
    并将您的表格更改为:

    <form>
        <input type="password" id="password_input" />
        <button type="button" onclick="pw_check();">submit</button>
    </form>
    
    
    提交
    

  • 定义“不工作”。您必须在输入中输入id=密码,而不是按钮。按钮具有
    id=“password”
    。您造成了重复的ID。是的,按钮(很抱歉没有看到),但他想读取输入,而不是按钮。这不会解决问题,因为函数从未被调用过。@AdrianPruss好的,但将ID放在两者上只会导致更多问题。