我正在使用 jQuery。如何获取当前 URL 的路径并将其分配给变量?
示例网址:
http://localhost/menuname.de?foo=bar&number=0
我正在使用 jQuery。如何获取当前 URL 的路径并将其分配给变量?
示例网址:
http://localhost/menuname.de?foo=bar&number=0
要获取路径,您可以使用:
var pathname = window.location.pathname; // Returns path only (/path/example.html)
var url      = window.location.href;     // Returns full URL (https://example.com/path/example.html)
var origin   = window.location.origin;   // Returns base URL (https://example.com)
纯 jQuery 风格:
$(location).attr('href');
位置对象还具有其他属性,例如主机、哈希、协议和路径名。
http://www.refulz.com:8082/index.php#tab2?foo=789
Property    Result
------------------------------------------
host        www.refulz.com:8082
hostname    www.refulz.com
port        8082
protocol    http:
pathname    index.php
href        http://www.refulz.com:8082/index.php#tab2
hash        #tab2
search      ?foo=789
var x = $(location).attr('<property>');
这仅在您拥有 jQuery 时才有效。例如:
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script>
  $(location).attr('href');      // http://www.refulz.com:8082/index.php#tab2
  $(location).attr('pathname');  // index.php
</script>
</html>
如果您需要 URL 中存在的哈希参数,window.location.href可能是更好的选择。
window.location.pathname
=> /search
window.location.href 
 => www.website.com/search#race_type=1
您将需要使用 JavaScript 的内置window.location对象。