如何使用 window.location 透過 JavaScript 重定向到不同的 URL?


你可能遇到過這樣的情況:點選了一個 URL 想要訪問頁面 X,但實際上卻訪問了另一個頁面 Y。這發生於頁面重定向。

在客戶端使用 Javascript 頁面重定向非常簡單。要將你的網站訪客重定向到新頁面,只需按如下方式在 head 部分中新增一行即可 −

示例

你可以嘗試執行以下程式碼來了解如何使用 window.location 重定向到另一個 URL。在此,我們將重定向到主頁

線上演示

<html>
   <head>
      <script>
         <!--
            function Redirect() {
               window.location.assign("https://tutorialspoint.tw");
            }
         //-->
      </script>
   </head>
   <body>
      <p>Click the following button, you will be redirected to home page.</p>
      <input type = "button" value="Redirect Me" onclick="Redirect();" />
   </body>
</html>

更新於: 2020 年 6 月 12 日

414 次瀏覽

開啟 職業生涯

完成課程認證

開始
廣告
© . All rights reserved.