如何使用JavaScript重定向到另一个网页?


window.location 对象包含当前位置或 URL 信息。我们可以使用此对象的属性将用户重定向到另一个网页。window.location 可以不带前缀 window 编写。

我们使用 window.location 对象的以下属性将用户重定向到另一个网页:

  • window.location.href - 它返回当前页面的 URL (href)。

  • window.location.replace() - 它用新文档替换当前文档。

  • window.location.assign() 加载新文档。

以下语法用于重定向到另一个网页。在所有程序示例中,我们都省略了 window 前缀,只使用 location。您可以尝试使用全名(即 window.location)运行程序。

语法

location.href = "url";
location.replace("url");
location.assign("url");

参数

url - 这是新网页的 URL。

使用 location.href 重定向

window.location.href 属性可用于重定向到另一个页面。我们可以使用以下语法进行重定向:

Window.location.href = "url";
Location.href = "url";
location = "url";

上述语法彼此等效,您可以根据需要使用任何语法将用户重定向到另一个网页。

让我们通过一个完整的示例来理解:

示例

在下面的示例中,我们使用 location.href 属性将用户重定向到另一个网页 (www.tutorix.com)。

<html>
   <head>
      <script type="text/javascript">
         function Redirect() {
            location.href="https://www.tutorix.com";
         }
      </script>
   </head>
   <body>
      <p>Click the following button to redirect to tutorix.com.</p>
      <form>
         <input type="button" value="Redirect Me" onclick="Redirect();" />
      </form>
   </body>
</html>

输出

运行上述程序时,将产生以下结果:

单击“重定向我”按钮后,将重定向到新网页。

使用 location.replace() 方法重定向

location.replace(url) 方法可用于用从 url 加载的另一个网页替换当前网页。我们可以使用以下语法进行重定向:

Window.location.replace("url");
Location.replace("url")

上面提到的两种语法是等效的,我们可以根据需要使用任何一种语法将用户重定向到另一个网页。

让我们通过一个完整的示例来理解:

示例

在下面的示例中,我们使用 location.replace(url) 方法将用户重定向到另一个网页 (www.tutorix.com)。

<html>
   <head>
      <script type="text/javascript">
         function Redirect() {
            location.replace("https://www.tutorix.com");
         }
      </script>
   </head>
   <body>
      <p>Click the following button to redirect to tutorix.com.</p>
      <form>
         <input type="button" value="Redirect Me" onclick="Redirect();" />
      </form>
   </body>
</html>

输出

运行上述程序时,将产生以下结果:

单击“重定向我”按钮后,将重定向到新网页。

使用 location.assign() 重定向

location.assign(url) 方法加载 url 中提供的资源。它可以用来重定向到另一个网页。我们可以使用以下语法进行重定向:

Window.location.assign("url");
Location.assign("url")

上面提到的两种语法相同,我们可以根据需要使用任何一种语法重定向到另一个网页。

示例

在下面的示例中,我们使用 location.assign(url) 方法将用户重定向到另一个网页 (https://www.totorix.com)。

<html>
   <head>
      <script type="text/javascript">
         function Redirect() {
            location.assign("https://www.tutorix.com");
         }
      </script>
   </head>
   <body>
      <p>Click the following button to redirect to tutorix.com.</p>
         <form>
            <input type="button" value="Redirect Me" onclick="Redirect();" />
         </form>
      </body>
</html>

输出

运行上述程序时,将产生以下结果:

单击“重定向我”按钮后,将重定向到新网页。

更新于:2022年4月20日

2万+ 次浏览

启动你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.