我正在使用jQuery。如何获取当前URL的路径并将其分配给变量?

示例URL:

http://localhost/menuname.de?foo=bar&number=0

当前回答

// get current URL

$(location).attr('href');
var pathname = window.location.pathname;
alert(window.location);

其他回答

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

window.location.origin

对于整个路径使用:

window.location.href

还有位置__

.host
.hostname
.protocol
.pathname

非常常用的前3个是

1. window.location.hostname 
2. window.location.href
3. window.location.pathname

仅对于主机名,请使用:

window.location.hostname
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;

这是一个比许多人想象的更复杂的问题。一些浏览器支持内置JavaScript位置对象和通过window.location或document.location访问的相关参数/方法。然而,不同风格的Internet Explorer(6,7)不以相同的方式支持这些方法,(window.location.href?window.location.replace()不受支持),因此您必须通过始终编写条件代码来以不同的方式访问它们,以手持Internet Explorer。

因此,如果您有jQuery可用并已加载,那么您最好使用jQuery(location),正如其他人提到的那样,因为它解决了这些问题。然而,如果您正在通过JavaScript(即使用Google Maps API和位置对象方法)进行一些客户端地理位置重定向,那么您可能不想加载整个jQuery库并编写检查每个版本的InternetExplorer/Firefox/等的条件代码。

InternetExplorer让前端编码猫不高兴,但jQuery是一盘牛奶。