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

示例URL:

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

当前回答

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

window.location.pathname
=> /search

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

其他回答

下面是一个使用jQuery和JavaScript获取当前URL的示例:

$(document).ready(function() {

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

    //Pure JavaScript
    var pathname = window.location.pathname;

    // To show it in an alert window
    alert(window.location);
});


$.getJSON("idcheck.php?callback=?", { url:$(location).attr('href')}, function(json){
    //alert(json.message);
});

这是一个比许多人想象的更复杂的问题。一些浏览器支持内置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是一盘牛奶。

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

仅对于主机名,请使用:

window.location.hostname

在纯jQuery样式中:

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

location对象还具有其他财产,如host、hash、protocol和pathname。