JavaScript location.pathname 属性
Location 对象的 pathname 属性用于设置或取得当前 URL 的路径部分,语法如下:
location.pathname = path
location.pathname 实例
例子 1
该例子通过 location.pathname 属性得到 URL 中的路径部分。
假设当前页面的 URL 是:http://www.5idev.com/test/test.shtml
<script type="text/javascript"> document.write(location.pathname); </script>
运行该例子,输出:
/test/test.shtml
例子 2
该例子通过 location.pathname 属性来设置 URL 中的路径:
假设当前页面的 URL 是:http://www.5idev.com/test.shtml
<html> <script type="text/javascript"> function setPathname(){ location.pathname = "/test/test.shtml"; } </script> <body> <button onclick="setPathname()">设定新的路径</button> </body> </html>
运行该例子,点击 设定新的路径 按钮,触发 setPathname() 函数,浏览器地址栏的 URL 将变为:http://www.5idev.com/test/test.shtml,而浏览器也将访问该 URL。
提示
- 当利用 location.pathname 属性设置新的路径时,总是以设定的参数代替 URL 中的路径部分,即该属性不可设定相对路径。
- location.pathname 得到的结果与 PHP $_SERVER<'SCRIPT_NAME'> 一致,即不会取得 URL 中的(查询)参数部分。
参考阅读
- PHP dirname 函数:返回 URL 路径中的目录
- PHP $_SERVER['PHP_SELF']:获取 php 文件相对于网站根目录的位置地址