如何在Javascript中获取当前目录名称?
我想用Javascript获取文件的当前目录,这样我就可以使用它为我的网站的每个部分触发不同的jQuery功能。如何在Javascript中获取当前目录名称?
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();
...
任何想法?
假设你在谈论当前的URL,你可以使用window.location
解析出URL的一部分。 见:http://java-programming.suite101.com/article.cfm/how_to_get_url_parts_in_javascript
您可以使用window.location.pathname.split('/');
这将产生一个阵列,所有的/的的项目
这会为实际的工作路径文件系统,如果你不是在说网址字符串。
var path = document.location.pathname;
var directory = path.substring(path.indexOf('/'), path.lastIndexOf('/'));
window.location.pathname将为您提供目录以及页面名称。然后你可以使用.substring()来获取目录:
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
希望这有助于!
Joomla网站产生的URL是这样的: HTTP://localhost/sub/sub/sub/index.php/ali-mm-d#tab2(除其他奇怪的事情) 因此这种方法产生不是一个目录,而是: http://localhost/sub/sub/sub/index.php – dsdsdsdsd 2012-07-26 11:21:50
这是我的解决方案,谢谢。 – DeyaEldeen 2017-05-25 19:24:17
对于两个/和\:
window.location.pathname.replace(/[^\\\/]*$/, '');
要返回没有结尾的斜线,这样做:
window.location.pathname.replace(/[\\\/][^\\\/]*$/, '');
这适用于IE thunderblaster 2015-05-13 19:31:18
如果你想完整的网址,例如: 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);
如果你不需要斜线结尾,除去+1
location.lastIndexOf("/")+1
后。
如果您只想要运行脚本的当前目录名称,例如workingdirectory
使用:
var location = window.location.pathname;
var path = location.substring(0, location.lastIndexOf("/"));
var directoryName = path.substring(path.lastIndexOf("/")+1);
位置会导致Google Chrome重新加载页面,将变量名称更改为其他位置,如location1 – mparkuk 2016-11-15 10:40:11
该一衬垫的工作原理:
var currentDirectory = window.location.pathname.split('/').slice(0, -1).join('/')
变种路径= document.location.pathname; var dir = path.substring(path.indexOf('/'),path.lastIndexOf('/')); – gtzinos 2016-03-20 16:10:49