Get current URL in JavaScript?

I am using jQuery. How do I get the path of the current URL and assign it to a variable?

Example URL:

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

要获得路径,您可以使用:

var pathname = window.location.pathname; // Returns path only
var url      = window.location.href;     // Returns full URL

In pure jQuery style:

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

The location object also has other properties, like host, hash, protocol, and pathname.


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>');

This will work only if you have jQuery. For example:

<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">
</script>
  $(location).attr('href');      // http://www.refulz.com:8082/index.php#tab2
  $(location).attr('pathname');  // index.php
</script>
</html>
链接地址: http://www.djcxy.com/p/1892.html

上一篇: 修改网址而不重新加载页面

下一篇: 在JavaScript中获取当前网址?