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

示例URL:

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

当前回答

 var currenturl = jQuery(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

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

$(location).attr('href').replace($(location).attr('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是一盘牛奶。

所有浏览器都支持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>

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

文档.URL$(“*”).context.baseURI位置.href