我正在使用jQuery。如何获取当前URL的路径并将其分配给一个变量?
示例URL:
示例URL:
http://localhost/menuname.de?foo=bar&number=0
http://localhost/menuname.de?foo=bar&number=0
这种方法也可以:
var currentURL = window.location.href;
您可以记录window.location并查看所有选项,仅使用URL,请使用:
window.location.origin
使用整个路径,请使用:
window.location.href
还有位置。__
.host
.hostname
.protocol
.pathname
所有浏览器都支持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>
location.path
,而不是location.pathname
-- 这个答案需要更新吗? - Edward我有这个代码用于去除GET参数。
var loc = window.location;
var currentURL = loc.protocol + '//' + loc.host + loc.pathname;
您可以使用JavaScript直接获取您的路径,window.location
或location
将为您提供当前URL的对象。
console.log("Origin - ",location.origin);
console.log("Entire URL - ",location.href);
console.log("Path Beyond URL - ",location.pathname);
URL 和哈希标签。
var pathname = window.location.pathname + document.location.hash;
var currenturl = jQuery(location).attr('href');
var path = location.pathname
返回当前 URL 的路径(无需 jQuery)。使用 window.location
是可选的。