我试图在成功登录后定向到另一个文件。但是,显示登录成功警报后,我似乎无法转到 b.html。它似乎保留在同一页面中。我已经尝试过 document.location.href
、window.location.replace
但它似乎不起作用
<script>
window.onload = function() {
document.addEventListener("deviceready", init, false);
}
function init() {
document.getElementById("btnSave").addEventListener("click", saveData, false);
document.getElementById("btnGet").addEventListener("click", getData, false);
}
function getData() {
var email1 = document.getElementById("email1").value;
var pass1 = document.getElementById("password1").value;
var email2 = window.localStorage.getItem("email");
var pass2 = window.localStorage.getItem("pass");
if (email1 == email2 && pass1 == pass2) {
alert("Login successfully");
window.location.href = "/b.html";
} else {
alert("Invalid login credentials");
}
}
</script>
<form class="login-form">
<input type="email" id="email1" name="email1" placeholder="Email Address" required/>
<input type="password" id="password1" name="password1" placeholder="Password" required/>
<button id="btnGet" type="submit" name="submit">Login</button>
</form>
最佳答案
重定向不起作用的原因是单击 Login
按钮提交了表单。这是网络浏览器的正常行为。在您的情况下,您需要防止这种默认行为。
使用jQuery
,你可以这样做:
$('form.login-form').submit((e) => {
e.preventDefault();
});
由于您根本没有在代码中使用 jQuery
,您可能会对这样的版本感兴趣:
form.addEventListener('submit', e => {
e.preventDefault();
});
另一种解决方案是不向登录按钮添加 type="submit"
属性。
但是您能做的最好的事情(以及互联网用户的习惯)是在提交表单后重定向用户。然后,这不仅在用户单击按钮时起作用,而且在用户按下 ENTER
时也起作用,等等。
那么你的代码应该是这样的:
(() => {
let form;
function init() {
form = document.querySelector('login-form');
if (!form) {
throw new ElementNotFoundException();
}
form.addEventListener('submit', onSubmitHandler);
}
function onSubmitHandler(e) {
e.preventDefault();
// get values, validate...
window.location.href = 'b.html';
}
init();
});
关于javascript - jQuery 重定向到另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40720806/