我怎样才能在Javascript中获取当前的目录名称?
我试图在Javascript中获取该文件的当前目录,所以我可以用它来触发我的网站的每个部分不同的jQueryfunction。
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(); ... 有任何想法吗?
window.location.pathname将得到你的目录,以及页面名称。 然后你可以使用.substring()来获取目录:
 var loc = window.location.pathname; var dir = loc.substring(0, loc.lastIndexOf('/')); 
希望这可以帮助!
 你可以使用window.location.pathname.split('/'); 
这将产生一个数组与/之间的所有项目
对于/和\:
 window.location.pathname.replace(/[^\\\/]*$/, ''); 
要返回没有斜线,做:
 window.location.pathname.replace(/[\\\/][^\\\/]*$/, ''); 
如果您不在说URLstring,这将适用于文件系统上的实际path。
 var path = document.location.pathname; var directory = path.substring(path.indexOf('/'), path.lastIndexOf('/')); 
 假设你正在谈论当前的URL,你可以使用window.locationparsing出部分URL。 请参阅: http : //java-programming.suite101.com/article.cfm/how_to_get_url_parts_in_javascript 
 如果您想要完整的URL,例如http://website/basedirectory/workingdirectory/ use: 
 var location = window.location.href; var directoryPath = location.substring(0, location.lastIndexOf("/")+1); 
 如果你想要没有域的本地patheg /basedirectory/workingdirectory/ use: 
 var location = window.location.pathname; var directoryPath = location.substring(0, location.lastIndexOf("/")+1); 
 如果最后不需要斜线,请在location.lastIndexOf("/")+1之后移除+1 。 
 如果您只想要运行脚本的当前目录名称,例如workingdirectory使用: 
 var location = window.location.pathname; var path = location.substring(0, location.lastIndexOf("/")); var directoryName = path.substring(path.lastIndexOf("/")+1); 
window.location .pathname
这个单行的作品:
 var currentDirectory = window.location.pathname.split('/').slice(0, -1).join('/')