[英]window.location.replace not working with jquery
由于某种原因,我在这里有一个小问题。 我有另一个页面几乎具有完全相同的代码,它将用户重定向到我希望他们去的页面。 由于某种原因,这一点没有。 我尝试注释掉if语句,然后一切都下降到只有用click动作将window.location.replace替换掉,仍然没有运气。
JS
$(document).ready(() => {
$("#login-button").click(() =>{
if($("#pwd").val() === 'pass' && $("#username").val() === 'taylor') {
alert("Welcome: " + $("#username").val());
window.location.replace('../index.html');
} else {
alert("You have the wrong password and username");
}
});
});
的HTML
<form id="login-form">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button id="login-button" class="btn btn-danger">Login</button>
</form>
您误会了location.replace()
的用途。 要重定向,请改用location.href
。
window.location.href = '../index.html';
Location.replace()方法用提供的URL中的资源替换当前资源。 与Assign()方法的区别在于,使用replace()之后,当前页面将不会保存在会话历史记录中,这意味着用户将无法使用后退按钮导航到该页面。
您还需要阻止表单提交。 这导致页面被发回到自身。 在表单submit
事件处理程序中添加以下内容。
e.preventDefault();
您只需要停止默认表单提交
html
<form id="login-form">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Remember me</label>
</div>
<button id="login-button" class="btn btn-danger">Login</button>
</form>
jQuery的
$(function() {
$("#login-button").click((e) {
if ($("#pwd").val() === 'pass' && $("#username").val() === 'taylor') {
alert("Welcome: " + $("#username").val());
window.location.href('../index.html');
e.preventDefault();
} else {
alert("You have the wrong password and username");
e.preventDefault();
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.