我想使用用戶輸入來決定用戶是否被重定向到另一個頁面。在這種情況下,用戶輸入用戶名和密碼。如果用戶名和密碼正確,則重定向用戶。為此,我使用簡單的 javascript 和 html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,minimum-scale=1">
<title>Login</title>
<!-- the form awesome library is used to add icons to our form -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css"> -->
<!-- include the stylesheet file -->
<link href="login.css" rel="stylesheet" type="text/css">
<script>
function testResults (form) {
var given_username = form.username.value;
var given_password = form.password.value;
var correct_username = "123";
var correct_password = "123";
if (given_username == correct_username && given_password == correct_password) {
window.location.assign("redirected.html");
}
else {
alert("Wrong username and/or password.")
}
}
</script>
</head>
<body>
<div class="login">
<h1>Login</h1>
<form action="" method="get">
<label for="username">
<!-- font awesome icon -->
<i class="fas fa-user"></i>
</label>
<input type="text" name="username" placeholder="Username" id="username" required>
<label for="password">
<i class="fas fa-lock"></i>
</label>
<input type="password" name="password" placeholder="Password" id="password" required>
<input type="submit" value="Login" onclick="testResults(this.form)" />
</form>
</div>
</body>
</html>
但是,當我填寫正確的用戶名和密碼時,在本例中為“123”,我根本不會被重定向。什么都沒發生。
但是,當我根本不使用 if 陳述句時:
<script>
function testResults (form) {
window.location.assign("redirected.html");
}
</script>
它作業正常。也就是說,每當您按下提交按鈕時,您都會被重定向。但是,在這種情況下,用戶根本不需要填寫憑據,所以在我的情況下,這并沒有多大用處。
我試過window.location, location.assign, location.href,location.replace和變體,但都產生相同的結果。
我該如何解決或解決這個問題?
uj5u.com熱心網友回復:
this.form是錯的。另外,您可以考慮使用 onsubmit 事件:
<form action="" method="get" onsubmit="testResults(this); return false">
<label for="username">
<!-- font awesome icon -->
<i class="fas fa-user"></i>
</label>
<input type="text" name="username" placeholder="Username" id="username" required>
<label for="password">
<i class="fas fa-lock"></i>
</label>
<input type="password" name="password" placeholder="Password" id="password" required>
<input type="submit" value="Login" />
</form>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/494782.html
標籤:javascript html 形式 if 语句 重定向
上一篇:垂直間距單個段落的行
