如何使用jQuery获取当前URL?

2041
我正在使用jQuery。如何获取当前URL的路径并将其分配给一个变量?
示例URL:
http://localhost/menuname.de?foo=bar&number=0

2
你可以在 http://tech-blog.maddyzone.com/javascript/get-current-url-javascript-jquery 上查看如何使用JavaScript和jQuery获取当前URL。 - Rituraj ratan
4
我认为问题应该恢复为询问jQuery,因为无论是否需要jQuery来完成任务,都有一个答案。 - goodeye
1
可能是使用JavaScript获取当前URL?的重复问题。 - vimal1083
4
没有 jQuery 对获取位置的方法;根据 jQuery 的 bug 跟踪器:»它可能起作用,但从未得到支持或文档化。只需使用 document.location.href 更快、更简单、更易于理解。« 换句话说,一些人使用 jQuery 获取位置,但他们依赖于一个 bug,而不是特性。请参见:http://bugs.jquery.com/ticket/7858 - feeela
33个回答

2786

要获取路径,可以使用:

var pathname = window.location.pathname; // Returns path only (/path/example.html)
var url      = window.location.href;     // Returns full URL (https://example.com/path/example.html)
var origin   = window.location.origin;   // Returns base URL (https://example.com)

82
位置对象的属性:https://developer.mozilla.org/zh-CN/docs/Web/API/Location。 - bentford
103
远非消灭它,jQuery给了Javascript新的生命。新的C#/Java程序员是否理解指针?不是。他们需要吗?不一定,因为新的抽象已经足够强大,不需要太在意指针。 - flesh
205
“如何在jQuery中实现XYZ”这样的问题,然而回答往往是使用普通JavaScript。你可能知道如何用普通JavaScript做某件事情;但由于浏览器不一致性,您可能更喜欢用“jQuery”的方式来做。我记得在没有jQuery或框架之前,我会首先检查浏览器,然后用几种方法做我想要的事情。所以,jQuery是否正在杀死普通js?是的,谢天谢地,但它也使得普通js变得可用。 - Parris
12
window.location.pathname只会获取问号“?”之前的 URL,而不会像问题所要求的那样获取查询参数。 - johntrepreneur
显示剩余7条评论

839

使用纯jQuery风格:

$(location).attr('href');

location 对象还有其他属性,例如 host、hash、protocol 和 pathname。


57
显然,在jQuery中使用$(location)是不受支持的,也不建议这样做:http://bugs.jquery.com/ticket/7858 - Peter
10
@Peter Bug被标记为无效。 - Kevin Ji
23
“invalid”一词适用于支持$(location)的请求,这个请求不应该使用。 - Peter
7
此答案不必要,问题和答案可以更新为不使用jQuery。原因可以在此找到:http://bugs.jquery.com/ticket/7858#comment:4 - Vishwanath
+1 因为我甚至不知道你可以在位置上使用 .attr()。但最好使用 window.location - Haralan Dobrev
9
@HaralanDobrev说:“你不应该在location上使用.attr()。 (1) 它不是一个元素,所以$(location)充其量也只是模糊的,而且(2) 即使它工作了,你也应该使用.prop()来获取属性。.attr()是用于HTML属性的。” - cHao

511
http://www.refulz.com:8082/index.php#tab2?foo=789

Property    Result
------------------------------------------
host        www.refulz.com:8082
hostname    www.refulz.com
port        8082
protocol    http:
pathname    index.php
href        http://www.refulz.com:8082/index.php#tab2
hash        #tab2
search      ?foo=789

var x = $(location).attr('<property>');

只有在引入jQuery时才能运行。例如:

<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script>
  $(location).attr('href');      // http://www.refulz.com:8082/index.php#tab2
  $(location).attr('pathname');  // index.php
</script>
</html>

15
同之前的解释一样,但包括对象的所有要素。非常好的回答。 - Oskar Calvo
7
路径名应该是 /index.php 而不是 index.php - Andrea
4
"jQuery是有史以来最优质的代码,如果你不使用它,那么你就是个白痴。jQuery绝对是最好的选择。"(这是一种讽刺的说法) - Oriol
5
根据http://bugs.jquery.com/ticket/7858,这个功能只是偶然起作用的。此外,“attr”只应该用于DOM对象上,用于可以通过HTML属性设置的事物。 - MauganRa

78
如果您需要 URL 中的哈希参数,window.location.href 可能是更好的选择。
window.location.pathname
=> /search

window.location.href 
 => www.website.com/search#race_type=1

3
如果有人只需要哈希标签,可以调用window.location.href。 - Amit Patel
18
我认为@AmitPatel的意思是window.location.hash - ptim

60

3
此功能不会返回位置中问号后面的项目。 - Majid
@majidgeek在Firefox、Chrome和IE中都能正常工作。你能提供一个测试用例来证明它出现了问题吗? - Barney
4
可以确认至少在控制台中,window.location.pathname无法获取问号后面的内容。 - worc

47

在JavaScript中添加此函数,它将返回当前路径的绝对路径。

function getAbsolutePath() {
    var loc = window.location;
    var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
    return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
}

希望它能对你有用。


1
这对我有很大帮助,因为我在一个脚本中懒得硬编码一些基本URL。我更喜欢在根目录上不加斜杠并将其插入路径中,所以我只是在第二行中添加了 var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/')); - cogdog

42

window.location是JavaScript中的一个对象,它返回以下数据

window.location.host          #returns host
window.location.hostname      #returns hostname
window.location.path          #return path
window.location.href          #returns full current url
window.location.port          #returns the port
window.location.protocol      #returns the protocol

在 jQuery 中,你可以使用

$(location).attr('host');        #returns host
$(location).attr('hostname');    #returns hostname
$(location).attr('path');        #returns path
$(location).attr('href');        #returns href
$(location).attr('port');        #returns port
$(location).attr('protocol');    #returns protocol

1
window.location.origin 是什么? - Ali Sheikhpour

32

这是一个比许多人想象的更加复杂的问题。几个浏览器支持内置的JavaScript位置对象和相关参数/方法,可以通过window.locationdocument.location访问。不过,不同版本的Internet Explorer(6,7)不能以同样的方式支持这些方法,(window.location.hrefwindow.location.replace()不被支持)因此,你必须编写有条件的代码来手动处理Internet Explorer的问题。

所以,如果你可以使用jQuery并已加载,那么最好使用jQuery(location),因为它解决了这些问题。但是,如果你正在例如通过JavaScript进行客户端地理定位重定向(即,使用Google Maps API和位置对象方法),则可能不想加载整个jQuery库并编写检查每个版本的Internet Explorer / Firefox等的条件代码。

Internet Explorer使前端编码猫不高兴,但jQuery是一大块奶酪。


另外:http://bugs.jquery.com/ticket/8138。在jQuery 1.8.0源代码中有注释://#8138,如果已设置document.domain,则IE可能在访问window.location的字段时抛出异常。 - Jan Święcki

30

仅使用主机名,可以使用:

window.location.hostname

25
"java-script提供了许多方法来获取当前在浏览器地址栏中显示的URL。"
"

测试URL:

"
http://
stackoverflow.com/questions/5515310/get-current-url-with-jquery/32942762
?
rq=1&page=2&tab=active&answertab=votes
#
32942762

resourceAddress.hash();
console.log('URL Object ', webAddress);
console.log('Parameters ', param_values);

功能:

var webAddress = {};
var param_values = {};
var protocol = '';
var resourceAddress = {

    fullAddress : function () {
        var addressBar = window.location.href;
        if ( addressBar != '' && addressBar != 'undefined') {
            webAddress[ 'href' ] = addressBar;
        }
    },
    protocol_identifier : function () { resourceAddress.fullAddress();

        protocol = window.location.protocol.replace(':', '');
        if ( protocol != '' && protocol != 'undefined') {
            webAddress[ 'protocol' ] = protocol;
        }
    },
    domain : function () {      resourceAddress.protocol_identifier();

        var domain = window.location.hostname;
        if ( domain != '' && domain != 'undefined' && typeOfVar(domain) === 'string') {
            webAddress[ 'domain' ] = domain;
            var port = window.location.port;
            if ( (port == '' || port == 'undefined') && typeOfVar(port) === 'string') {
                if(protocol == 'http') port = '80';
                if(protocol == 'https') port = '443';           
            }
            webAddress[ 'port' ] = port;
        }
    },
    pathname : function () {        resourceAddress.domain();

        var resourcePath = window.location.pathname;
        if ( resourcePath != '' && resourcePath != 'undefined') {
            webAddress[ 'resourcePath' ] = resourcePath;
        }
    },
    params : function () {      resourceAddress.pathname();

        var v_args = location.search.substring(1).split("&");

        if ( v_args != '' && v_args != 'undefined')
        for (var i = 0; i < v_args.length; i++) {
            var pair = v_args[i].split("=");

            if ( typeOfVar( pair ) === 'array' ) {
                param_values[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
            }
        }
        webAddress[ 'params' ] = param_values;
    },
    hash : function () {        resourceAddress.params();

        var fragment = window.location.hash.substring(1);
        if ( fragment != '' && fragment != 'undefined')
            webAddress[ 'hash' ] = fragment;        
    }
};
function typeOfVar (obj) {
      return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
  • 协议:Web-browsers使用Internet Protocol,遵循一些规则,用于 WebHosted 应用程序和 Web 客户端(浏览器)之间的通信。(http=80,https(SSL)=443,ftp=21等)

例如:默认端口号

<protocol>//<hostname>:<port>/<pathname><search><hash>
https://en.wikipedia.org:443/wiki/Pretty_Good_Privacy
http://stackoverflow.com:80/
  • (//)「主机」是指互联网上资源所在的终端设备的名称。例如www.stackoverflow.com - DNS应用程序的IP地址(或)localhost:8080 - localhost

域名是根据域名系统(DNS)树的规则和程序注册的。管理您的域名的人使用DNS服务器来进行寻址。在DNS服务器层级结构中,stackoverlfow.com的根名称是com。

gTLDs      - com « stackoverflow (OR) in « co « google

在本地系统中,您需要维护Host文件中不公开的域名。 localhost.yash.com是子域名(web-server),yash.com是主域名(Proxy-Server)。 myLocalApplication.com的IP地址为172.89.23.777。

  • (/) - 路径提供有关Web客户端要访问的主机内特定资源的信息
  • (?) - 可选查询是通过分隔符(&)传递属性值对序列的方式。
  • (#) - 可选片段通常是特定元素的id属性,Web浏览器将滚动此元素以查看。

如果参数具有Epoch ?date=1467708674,则使用。

var epochDate = 1467708674; var date = new Date( epochDate );

网址 在此输入图片描述


带有用户名和密码的身份验证URL,如果用户名/密码包含@符号
例如:

Username = `my_email@gmail`
Password = `Yash@777`

然后,您需要将@编码为%40参考链接1
http://my_email%40gmail.com:Yash%40777@www.my_site.com

encodeURI() (vs) encodeURIComponent() 示例

var testURL = "http:my_email@gmail:Yash777@//stackoverflow.com?tab=active&page=1#32942762";

var Uri = "/:@?&=,#", UriComponent = "$;+", Unescaped = "(-_.!~*')"; // Fixed
var encodeURI_Str = encodeURI(Uri) +' '+ encodeURI( UriComponent ) +' '+ encodeURI(Unescaped);
var encodeURIComponent_Str =  encodeURIComponent( Uri ) +' '+ encodeURIComponent( UriComponent ) +' '+ encodeURIComponent( Unescaped );
console.log(encodeURI_Str, '\n', encodeURIComponent_Str);
/*
 /:@?&=,# +$; (-_.!~*') 
 %2F%3A%40%3F%26%3D%2C%23 %2B%24%3B (-_.!~*')
*/

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接