我无法使用 .js 页面中的 Windows 位置重定向到单个页面。
但是,我检查了警报框,看看条件是否通过,并且在位置不起作用时它是否起作用。
var attempt = 3; // Variable to count number of attempts.
// Below function Executes on click of login button.
function validate() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email == "test1@gmail.com" && password == "test1") {
alert("Login successfully");
window.location.href = 'messages.php';
return false;
} else {
attempt--; // Decrementing by one.
alert("You have left " + attempt + " attempt;");
// Disabling fields after 3 attempts.
if (attempt == 0) {
document.getElementById("email").disabled = true;
document.getElementById("password").disabled = true;
document.getElementById("submit").disabled = true;
return false;
}
}
}
我觉得我错过了一些东西。
最佳答案
我怀疑您正在像这样调用validate
:
<form onsubmit="validate()" ...>
这不会使用validate
的返回值来取消提交。您需要返回
:
<form onsubmit="return validate()" ...>
由于提交并未被取消,因此表单提交是一个导航操作,它会覆盖您对 window.location.href
的分配。
在评论中您说过您正在这样做:
<button type="submit" name="submit" onclick="validate()" class="btn-secondary">Sign In</button>
如果是这样,将 return
添加到 onclick
应该可以在任何现代浏览器上修复它:
<button type="submit" name="submit" onclick="return validate()" class="btn-secondary">Sign In</button>
但是我会将其移至表单
上的onsubmit
。
旁注:该按钮上不需要 type="submit"
。 submit
是 button
元素的默认类型。
关于javascript - 无法使用 window.location 重定向到页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50036330/