首页 > 解决方案 > 用户输入正确密码后,如何使提交按钮重定向到另一个页面?

问题描述

你能帮我找出问题所在吗?登录后,它应该将您重定向到另一个页面,但没有任何反应。用户名是:Joshua,密码是:Joshua#123。

<html>

<head>
  <title>Login: MessengerX</title>
  <link rel="stylesheet" type="text/css" href="C:\Users\Tania\Documents\Website\style.css">
  <meta charset="UTF-8">
  <meta name="description" content="HTML website called MessengerX. Send messages to anyone who has logged in.">
  <meta name="author" content="Joshua Hurley">
  <meta name="keywords" content="HTML, MessengerX, Joshua Hurley, Website, Supremefilms">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="css/style.css" />
  <script type="text/javascript">
    var attempt = 3; // Variable to count number of attempts.
    // Below function Executes on click of login button.
    function validate() {
      var username = document.getElementById("username").value;
      var password = document.getElementById("password").value;
      if (username == "Joshua" && password == "Joshua#123") {
        alert("Login successfully");
        location.replace("www.youtube.com"); // Redirecting to other page.
      } else {
        attempt--; // Decrementing by one.
        alert("You have " + attempt + " attempt left;");
        // Disabling fields after 3 attempts.
        if (attempt == 0) {
          document.getElementById("username").disabled = true;
          document.getElementById("password").disabled = true;
          document.getElementById("submit").disabled = true;
          return false;
        }
      }
    }
  </script>

  <script src="js/login.js"></script>
</head>

<body>
  <div class="imgcontainer">
    <img src="C:\Users\Tania\Documents\Website\Screenshots\face.jpg" height="500" alt="Avatar" class="avatar">
  </div>
  <div class="container">
    <div class="main">
      <h1 style="color:"><b><i>Login: MessengerX</i></b></h1>
      <form id="form_id" method="post" name="myform">
        <label>User Name :</label>
        <input type="text" name="username" id="username" />
        <label>Password :</label>
        <input type="password" name="password" id="password" />
        <button type="submit" value="Login" id="submit" onclick="validate()" />
      </form>
      <b><i>Submit</i></b>
    </div>
  </div>
</body>

</html>

标签: javascripthtmlauthenticationredirect

解决方案


您可以在里面移动代码,也可以在最后window.addEventListener('load'移动脚本dom

建议:将整个 URL 与 HTTP 或 HTTPS 一起使用。

location.replace("https://www.youtube.com");

<script type="text/javascript">
    window.addEventListener('load', (event) => {
      var attempt = 3; // Variable to count number of attempts.

      /// code here
    });
  </script>

推荐阅读