JavaScript 中 window.location 的作用是什麼?


Window.location 是視窗的 location 屬性,它是 Location 物件的引用;它表示在該視窗中顯示的文件的當前 URL。

由於 window 物件位於作用域鏈的頂部,因此可以無需 window. 字首訪問 window.location 物件的屬性,例如 window.location.href 可以寫成 location.href。

以下部分將向您展示如何使用 window 物件的 location 物件屬性獲取頁面的 URL 以及主機名、協議等。您可以使用 window.location.href 屬性獲取當前頁面的完整 URL。

Windows.location.href 屬性

這是一個包含完整 URL 的 DOMString。如果更改,關聯的文件將導航到新頁面。它可以從與關聯文件不同的來源設定。

示例

這是 window.location.href 屬性的示例。在這裡,我們嘗試檢索頁面的 URL:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JavaScript Get Current URL</title> </head> <body> <script> function getURL() { alert("The URL of this page is: " + window.location.href); } </script> <button type="button" onclick="getURL();">Get Page URL</button> </body> </html>

Windows.location.protocol 屬性

如果我們點選標註為“獲取頁面URL”的按鈕,我們將得到當前URL作為輸出。類似地,您可以使用 location 物件的其他屬性,如協議、主機名、埠、路徑名、搜尋等來獲取URL的不同部分。

示例

以下是 window.location.protocol 屬性的用法:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Get Different Part of a URL</title> </head> <body> <script> document.write(window.location.protocol + "<br>"); </script> <p><strong>Note:</strong> If the URL does not contain a specific component (e.g., port number, and fragment identifier here), it will be set to ''.</p> </body> </html>

Windows.location.host 屬性

此屬性表示主機,即主機名、“:”和 URL 的埠。

示例

以下示例檢索並列印 URL 中主機位置的主機名。

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JavaScript Get Different Part of a URL</title> </head> <body> <script> document.write(window.location.host + "<br>"); </script> </body> </html>

window.location.assign() 方法

您可以使用 location 物件的 assign() 方法,即 window.location.assign(),從作為引數提供的 URL 載入另一個資源。在下面給出的示例中,我們嘗試在該位置載入新文件。

示例

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Load another Resource from a URL</title> </head> <body> <script> function loadHomePage() { window.location.assign("https://tutorialspoint.tw"); } </script> <button type="button" onclick="loadHomePage();">Load Home Page</button> <p><strong>Note:</strong> Open the output in a new tab by clicking the arrow next to "Show Output" button then click the above button to see how it works.</p> </body> </html>

window.location.replace() 方法

您還可以使用 replace() 方法載入新文件,這與 assign() 方法幾乎相同。不同之處在於它不會在瀏覽器的歷史記錄中建立條目,這意味著使用者將無法使用後退按鈕導航到它。以下是此方法的示例。

示例

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Replace URL with a New URL</title> </head> <body> <script> function HomePage(){ window.location.replace("https://tutorialspoint.tw"); } </script> <button type="button" onclick="HomePage();">Home Page</button> <p><strong>Note:</strong> Open the output in a new tab by clicking the arrow next to "Show Output" button then click the above button to see how it works.</p> </body> </html>

更新於:2022年8月26日

2K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.