我正在使用jQuery。如何获取当前URL的路径并将其分配给变量?
示例URL:
http://localhost/menuname.de?foo=bar&number=0
我正在使用jQuery。如何获取当前URL的路径并将其分配给变量?
示例URL:
http://localhost/menuname.de?foo=bar&number=0
当前回答
var CurrentBrowseurl=document.location.href;console.log(当前浏览器);
其他回答
这是一个比许多人想象的更复杂的问题。一些浏览器支持内置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将为您提供当前URL,您可以从中提取任何您想要的内容。。。
在纯jQuery样式中:
$(location).attr('href');
location对象还具有其他财产,如host、hash、protocol和pathname。
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
这也将起作用:
var currentURL = window.location.href;