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

use*_*303 64 javascript jquery

我正在尝试使用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();
...
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Rya*_*nal 77

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

var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!


Rob*_*Rob 20

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

这将产生一个包含/之间所有项目的数组


小智 16

在Node.js中,您可以使用:

console.log('Current directory: ' + process.cwd());
Run Code Online (Sandbox Code Playgroud)


bpe*_*n76 11

如果您不是在谈论URL字符串,这将适用于文件系统上的实际路径.

var path = document.location.pathname;
var directory = path.substring(path.indexOf('/'), path.lastIndexOf('/'));
Run Code Online (Sandbox Code Playgroud)


Dav*_*ret 9

对于/和\:

window.location.pathname.replace(/[^\\\/]*$/, '');
Run Code Online (Sandbox Code Playgroud)

要返回没有尾部斜杠,请执行以下操作:

window.location.pathname.replace(/[\\\/][^\\\/]*$/, '');
Run Code Online (Sandbox Code Playgroud)


fla*_*nze 6

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

var location = window.location.href;
var directoryPath = location.substring(0, location.lastIndexOf("/")+1);
Run Code Online (Sandbox Code Playgroud)

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

var location = window.location.pathname;
var directoryPath = location.substring(0, location.lastIndexOf("/")+1);
Run Code Online (Sandbox Code Playgroud)

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

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

var location = window.location.pathname;
var path = location.substring(0, location.lastIndexOf("/"));
var directoryName = path.substring(path.lastIndexOf("/")+1);
Run Code Online (Sandbox Code Playgroud)

  • location 导致 Google Chrome 重新加载页面,将变量名称更改为其他名称,例如 location1 (2认同)

jby*_*yrd 5

这种单线工作原理:

var currentDirectory = window.location.pathname.split('/').slice(0, -1).join('/')
Run Code Online (Sandbox Code Playgroud)