Javascript 有没有办法检查变量';s值与另一个';s
我正试图建立一个密码系统,但我不知道密码。无论密码是什么,它都包含在一个变量中。我正在努力:Javascript 有没有办法检查变量';s值与另一个';s,javascript,html,if-statement,Javascript,Html,If Statement,我正试图建立一个密码系统,但我不知道密码。无论密码是什么,它都包含在一个变量中。我正在努力: <input type="password" id="pass"> <button onclick="pass()">Go</button> <script> var password = document.getElementById("pass").value; var answer = "the password" function pass()
<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 password=document.getElementById(“pass”).value;
var answer=“密码”
函数传递(){
如果(密码==答案){
window.location.replace(“http://example.com");
}
否则{
document.getElementById(“note”).innerHTML=“错误的用户名或密码。是否重试?
”;
}
}
但它不起作用。有没有办法检查一个变量的值是否与另一个变量的值相同?
谢谢 您应该获得函数中输入的值,如下所示:
var answer=“密码”
函数传递(){
var password=document.getElementById(“pass”).value;
如果(密码==答案)
window.location.replace(“http://example.com");
其他的
document.getElementById(“note”).innerHTML=“错误的用户名或密码。是否重试?
”;
}
去
您只是有一个“计时”问题:您应该在单击按钮时读取用户输入的值,您需要将var password=document.getElementById(“pass”).value
行移动到函数调用中
const answer=“密码”;
函数传递(){
const password=document.getElementById(“pass”).value;
如果(密码==答案){
document.getElementById(“note”).innerHTML=“好密码!”;
}
否则{
document.getElementById(“note”).innerHTML=“错误的用户名或密码。是否重试?
”;
}
}
去
您好,有相同的错误,请尝试此选项
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>";
}
}
var answer=“密码”;
函数传递(){
var password=document.getElementById(“pass”).value;
如果(密码===答案){
window.location.replace(“http://example.com");
}
否则{
document.getElementById(“note”).innerHTML=“错误的用户名或密码。是否重试?
”;
}
}
document.getElementById(“pass”).value
您需要在pass()函数中读取它。因为您希望在单击按钮时获取值。当前,它在读取脚本时读取值,即在加载页面时,文本框中可能没有任何内容。