如何在 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