我无法使用.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;
}
}
}
我觉得我错过了什么。
答案 0 :(得分:2)
我怀疑你是这样打电话给validate
:
<form onsubmit="validate()" ...>
不会使用validate
的返回值来取消提交。您需要return
:
<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
上的form
。
旁注:该按钮上不需要type="submit"
。 submit
是button
元素的默认类型。
答案 1 :(得分:-1)
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; // ALWAYS return this. else it will proceed with page submit.
}
}