我使用以下代码来验证表单中的密码。如果密码正确 - 将用户移至站点 X。如果密码不正确(3 次尝试后),请将用户移至站点 Y。
由于某种原因,它仅适用于站点 Y。
我的代码:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<form>
Enter password to continue: <br>
<input type="text" id="user"/>
<input type="button" id="myButton" value="Enter site"/>
</form>
<script>
let tries = 0;
let error = 0;
let password = 'tiesto';
document.querySelector("#myButton").onclick = ()=> {
let passwordValue = document.querySelector('#user').value;
if (password === passwordValue) {
window.location.href = 'http://maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 3) { // 3 is the border.
error++;
}
if (error === 1) {
window.location.href = 'http://microsoft.com';
}
};
</script>
</body>
</html>
我尝试这样做:
- 检查整个代码中的语法错误。
- 将
===
更改为==
(我想,也许由于它是一个字符串,引号也被计算在内,当然我错了)。 window.location.href = 'http://maariv.co.il', true
;- 在
window.location.href
下添加return false
作为一个初学者,我问,为什么这个条件只起作用一半?也就是说,积极的部分(than)不起作用,但消极的部分(else)起作用。
更新:
这只是一个练习。的确。这不会投入生产。在生产中,我应该存储密码并从数据库请求密码。
最佳答案
将以下行 let passwordValue = document.querySelector('#user').value;
放入“mybutton”的 onclick 内。
let tries = 0;
let error = 0;
let password = 'tiesto';
document.querySelector("#myButton").onclick = ()=> {
let passwordInput = document.querySelector('#passwordInput').value;
if (password === passwordValue) {
window.location.href = 'http://maariv.co.il';
} else {
tries++;
alert('Try again please.');
}
if (tries === 3) { // 3 is the border.
error++;
}
if (error === 1) {
window.location.href = 'http://microsoft.com';
}
};
<form>
Enter password to continue: <br>
<input type="text" id="user" />
<input type="button" id="myButton" value="Enter site" />
</form>
关于javascript - document.location 或 window.location.href 在条件的 if 部分不起作用,但在 else 部分起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45935090/