簡體   English   中英

使用 if 語句重定向用戶的 HTML Javascript 不起作用

[英]HTML Javascript redirecting user with if statement does not work

我想使用用戶輸入來決定用戶是否被重定向到另一個頁面。 在這種情況下,用戶輸入用戶名和密碼。 如果用戶名和密碼正確,則重定向用戶。 為此,我使用簡單的 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.locationlocation.assignlocation.hreflocation.replace和變體,但都產生了相同的結果。

我該如何解決或解決這個問題?

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM