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

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


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

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


30秒到达战场
浏览 136回答 3
3回答

蓝山帝景

你只是有一个“时间”问题:你应该在点击按钮的那一刻读取用户输入的值,你需要将你的var password = document.getElementById("pass").value行移到函数调用中。const answer = "the password";function pass() {&nbsp; const password = document.getElementById("pass").value;&nbsp; if (password == answer) {&nbsp; &nbsp; document.getElementById("note").innerHTML = "<p>Good password!</p>";&nbsp; }&nbsp; else {&nbsp; &nbsp; document.getElementById("note").innerHTML = "<p style='color:red'>Wrong username or password. Try again?</p>";&nbsp; }}<input type="password" id="pass">&nbsp;<button onclick="pass()">Go</button><div id="note"></div>

噜噜哒

您应该在函数内获取输入的值,如下所示:var answer = "the password"function pass() {&nbsp; &nbsp; &nbsp;var password = document.getElementById("pass").value;&nbsp; &nbsp; &nbsp;if (password == answer)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; window.location.replace("http://example.com");&nbsp; &nbsp; &nbsp;else&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("note").innerHTML = "<p style='color:red'>Wrong username or password. Try again?</p>";}<input type="password" id="pass" />&nbsp;<button onclick="pass()">Go</button><div id="note"></div>

米脂

你好,有同样的错误,试试这个var answer = "the password";function pass() {&nbsp; &nbsp; var password = document.getElementById("pass").value;&nbsp; &nbsp; if (password === answer) {&nbsp; &nbsp; &nbsp; &nbsp; window.location.replace("http://example.com");&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("note").innerHTML = "<p style='color:red'>Wrong username or password. Try again?</p>";&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript