[英]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.