如何在 jQuery 中獲取當前 URL

Sundeep Dawadi 2023年1月30日 jQuery
  1. 在 jQuery 中 href 屬性獲取當前的 URL
  2. 在 jQuery 中訪問 URL 的特定屬性
如何在 jQuery 中獲取當前 URL

經常會有這樣的情況,當你想看看你的 jQuery 程式碼當前在哪裡載入。對於瀏覽器中的每一個開啟的視窗,瀏覽器都會提供對其 window 物件的訪問。作為 window 物件的一部分,location 物件給出了當前 URL 的資訊。

在 jQuery 中 href 屬性獲取當前的 URL

要獲得當前的 URL,你可以訪問瀏覽器的 location 物件的 href 屬性。

<script>
 var url = $(location).attr('href');
  // Returns full URL
(https://example.com/path/example.html)
 var pathname = $(location).attr('pathname');
  // Returns path only (/path/example.html)
 var origin = $(location).attr('origin');
  // Returns base URL (https://example.com)
</script>
注意
用普通的 JavaScript 方式,可以通過 window.location.href 來訪問它。

在 jQuery 中訪問 URL 的特定屬性

location 物件帶有 URL 的附加屬性。

屬性 說明
hash 錨點
host 主機名和埠號
hostname 主機名
href 整個 URL
origin URL 的協議、主機名和埠號
pathname 網址名
port 埠號
protocol 協議
search 查詢字串
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe