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

示例URL:

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

当前回答

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

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

所有全局变量都是窗口对象财产,所有全局函数都是其方法。

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

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

Java脚本

console.log(window.location.host)//返回主机console.log(window.location.hostname)//返回主机名console.log(window.location.pathname)//返回路径console.log(window.location.href)//返回完整的当前urlconsole.log(window.location.port)//返回端口console.log(window.location.protocol)//返回协议

JQuery(J查询)

console.log(“host=”+$(位置).attr('host'));console.log(“hostname=”+$(位置).attr('主机名'));console.log(“路径名=”+$(位置).attr('路径名'));console.log(“href=”+$(位置).attr('href'));console.log(“port=”+$(位置).attr('port'));console.log(“protocol=”+$(位置).attr('协议'));<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js“></script>

其他回答

如果要获取根站点的路径,请使用以下命令:

$(location).attr('href').replace($(location).attr('pathname'),'');
// get current URL

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

要从iframe中获取父窗口的URL,请执行以下操作:

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

注意:仅在同一域上工作

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

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

window.location.pathname
=> /search

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