有没有办法检查一个变量的值是否与另一个变量的值相同?

我正在尝试制作密码系统,但是我不知道密码。无论密码是什么,它都包含在变量中。我在尝试:

<input type="password" id="pass"> 
<button onclick="pass()">Go</button>
<script>
var password = document.getElementById("pass").value;
var answer = "the password"
function pass() {
if (password == answer) {
window.location.replace("http://example.com");
}
else {
document.getElementById("note").innerHTML = "<p style='color:red'>Wrong username or password. Try again?</p>";
}
}
</script>

而且没有用有没有办法检查一个变量的值是否与另一个变量的值相同? 谢谢!

评论
  • ~那么美
    ~那么美 回复

    您应该按以下方式获取函数内部输入的值:

    var answer = "the password"
    function pass() {
         var password = document.getElementById("pass").value;
         if (password == answer) 
              window.location.replace("http://example.com");
         else 
              document.getElementById("note").innerHTML = "<p style='color:red'>Wrong username or password. Try again?</p>";
    }
    <input type="password" id="pass" /> 
    <button onclick="pass()">Go</button>
    <div id="note"></div>
  • Upton
    Upton 回复

    嗨,有同样的错误,试试这个

    var answer = "the password";
    function pass() {
        var password = document.getElementById("pass").value();
        if (password === answer) {
            window.location.replace("http://example.com");
        }
        else {
            document.getElementById("note").innerHTML = "<p style='color:red'>Wrong username or password. Try again?</p>";
        }
    }
    
  • 敌敌畏
    敌敌畏 回复

    You just have a "timing" issue : you should read the value of the user input at the moment the button is clicked, yo you need to move your var password = document.getElementById("pass").value line into the function call.

    const answer = "the password"
    function pass() {
      const password = document.getElementById("pass").value;
        if (password == answer) {
          window.location.replace("http://example.com");
        }
        else {
          document.getElementById("note").innerHTML = "<p style='color:red'>Wrong username or password. Try again?</p>";
        }
      }
    }