如何使用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个回答

25

这种方法也可以:

var currentURL = window.location.href;

这将提供大多数人寻找的完整URL。 - aiternal

21

您可以记录window.location并查看所有选项,仅使用URL,请使用:

window.location.origin

使用整个路径,请使用:

window.location.href

还有位置。__

.host
.hostname
.protocol
.pathname

不应该使用它,因为location.origin在Internet Explorer中无法工作。 - licancabur

16

使用JavaScript/jQuery,将返回当前页面的绝对URL

  • document.URL

  • $("*").context.baseURI

  • location.href


15

所有浏览器都支持JavaScript窗口对象,它定义了浏览器的窗口。

全局对象和函数自动成为window对象的一部分。

所有全局变量都是window对象的属性,所有全局函数都是其方法。

整个HTML文档也是一个窗口属性。

因此,您可以使用window.location对象获取所有与URL相关的属性。

JavaScript

console.log(window.location.host);     //returns host
console.log(window.location.hostname);    //returns hostname
console.log(window.location.pathname);         //return path
console.log(window.location.href);       //returns full current url
console.log(window.location.port);         //returns the port
console.log(window.location.protocol)     //returns the protocol

jQuery

console.log("host = "+$(location).attr('host'));
console.log("hostname = "+$(location).attr('hostname'));
console.log("pathname = "+$(location).attr('pathname')); 
console.log("href = "+$(location).attr('href'));   
console.log("port = "+$(location).attr('port'));   
console.log("protocol = "+$(location).attr('protocol'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>


2
我看到你在使用location.path,而不是location.pathname-- 这个答案需要更新吗? - Edward
@Edward 更新完成 - Sumesh TG

14

我有这个代码用于去除GET参数。

var loc = window.location;
var currentURL = loc.protocol + '//' + loc.host + loc.pathname;

13

您可以使用JavaScript直接获取您的路径,window.locationlocation将为您提供当前URL的对象。

console.log("Origin - ",location.origin);
console.log("Entire URL - ",location.href);
console.log("Path Beyond URL - ",location.pathname);


13
如果有人想要将URL和哈希标签连接起来,可以结合两个函数:

URL 和哈希标签。

var pathname = window.location.pathname + document.location.hash;

澄清一下:您根本不需要使用jQuery,上面的JavaScript函数将返回OP所要求的内容? - GHC

11
 var currenturl = jQuery(location).attr('href');

11

11

var path = location.pathname 返回当前 URL 的路径(无需 jQuery)。使用 window.location 是可选的。


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