如何获取Javascript中的当前目录名称?


76

我正在尝试使用Javascript获取文件的当前目录,因此可以使用该目录为网站的每个部分触发不同的jquery函数。

if (current_directory) = "example" {
var activeicon = ".icon_one span";
};
elseif (current_directory) = "example2" {
var activeicon = ".icon_two span";
};
else {
var activeicon = ".icon_default span";
};

$(activeicon).show();
...

有任何想法吗?

Answers:


82

window.location.pathname将为您提供目录以及页面名称。然后,您可以使用.substring()获取目录:

var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));

希望这可以帮助!


我的joomla网站产生的网址是这样的: localhost / sub / sub / sub / sub / index.php / ali-mm-d#tab2(还有其他奇怪的事情),因此这种方法不是产生目录,而是:localhost / sub / sub / sub / index.php
dsdsdsdsd 2012年

仅供参考:如果loc === '/'那么dir === ''
raphinesse


21

您可以使用 window.location.pathname.split('/');

这将产生一个数组,其中所有/之间


11

如果您不讲URL字符串,这将适用于文件系统上的实际路径。

var path = document.location.pathname;
var directory = path.substring(path.indexOf('/'), path.lastIndexOf('/'));

var path = document.location.pathname; var dir = path.substring(path.indexOf('/'),path.lastIndexOf('/'));
gtzinos

9

对于/和\:

window.location.pathname.replace(/[^\\\/]*$/, '');

要返回时不带斜杠,请执行以下操作:

window.location.pathname.replace(/[\\\/][^\\\/]*$/, '');

这在IE <9中有效,而使用.lastIndexOf的答案无效。因此+1。
thunderblaster 2015年

8

完整网址

如果您想要完整的URL,例如,http://website/basedirectory/workingdirectory/使用:

var location = window.location.href;
var directoryPath = location.substring(0, location.lastIndexOf("/")+1);

本地路径

如果您想要没有域的本地路径,请/basedirectory/workingdirectory/使用:

var location = window.location.pathname;
var directoryPath = location.substring(0, location.lastIndexOf("/")+1);

如果您不需要在末尾使用斜杠,请删除+1after location.lastIndexOf("/")+1

目录名

如果只需要当前目录名称(运行脚本的位置),例如,请workingdirectory使用:

var location = window.location.pathname;
var path = location.substring(0, location.lastIndexOf("/"));
var directoryName = path.substring(path.lastIndexOf("/")+1);

1
location导致Google Chrome重新加载页面,将变量名称更改为location1
mparkuk '16

节省了我很多时间!谢谢
Shadoninja '20

6

这种单线工作原理:

var currentDirectory = window.location.pathname.split('/').slice(0, -1).join('/')

试图取消我的不赞成票,但由于我最近对此投票,所以不允许我这样做。这很有道理……
Lev



1

如果您想要完整的URL,例如,website.com/workingdirectory/使用: window.location.hostname+window.location.pathname.replace(/[^\\\/]*$/, '');


1

获取dirname当前URL的一种有趣方法是利用浏览器的内置路径解析。您可以通过以下方式做到这一点:

  1. 创建指向的链接.,即当前目录
  2. 使用HTMLAnchorElement链接的界面获取解析的URL或等效于的路径.

这是完成这一工作的一行代码:

Object.assign(document.createElement('a'), {href: '.'}).pathname

与此处介绍的其他一些解决方案相比,此方法的结果将始终带有斜杠。例如在此页面上运行将产生收益/questions/3151436/,在其上运行https://stackoverflow.com/将产生收益/

获取完整的URL而不是路径也很容易。只需读取href属性即可pathname

最后,如果您不使用此方法,即使在最古老的浏览器中也应适用Object.assign

function getCurrentDir () {
    var link = document.createElement('a');
    link.href = '.';
    return link.pathname;
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.