如何使用 window.location 將使用者重定向到不同的URL?


您可能遇到過這樣的情況:您點選某個 URL 來訪問頁面 X,但您實際上被定向到另一個頁面 Y。這是由於頁面重定向。

使用客戶端的 JavaScript 來進行頁面重定向非常簡單。只需在 head 部分新增一行即可將您的網站訪問者重定向到新頁面。

示例

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

線上演示

<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 年 1 月 13 日

925 次瀏覽

開始你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.