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

101

我正在尝试使用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();
...

有什么想法吗?

12个回答

0

0

我发现使用标准的URL对象查找当前页面的URL非常可靠。非常适合创建新的URL,包括相对路径和绝对路径。

url = window.location
console.log(url);
//strip pagename from pathname
currentdir = new URL(url.pathname.replace( /[^\/]*$/, ''), url.origin);
//now make new paths relative to currentdir
console.log(new URL("/dir1/dir2/hello.html", currentdir));
console.log(new URL("../../dir1/dir2/hello.html", currentdir));
console.log(new URL("../dir1/dir2/hello.html", currentdir));
console.log(new URL("./dir1/dir2/hello.html", currentdir));
console.log(new URL("dir1/dir2/hello.html", currentdir));
currentdir.port = 1234;
console.log(new URL("dir1/dir2/hello.html", currentdir));

假设当前页面为
https://interactive-examples.mdn.mozilla.net/pages/js/string-replace.html,预计会有当前输出。

https://interactive-examples.mdn.mozilla.net/pages/js/string-replace.html
"currentdir = https://interactive-examples.mdn.mozilla.net/pages/js/"
https://interactive-examples.mdn.mozilla.net/dir1/dir2/hello.html
https://interactive-examples.mdn.mozilla.net/dir1/dir2/hello.html
https://interactive-examples.mdn.mozilla.net/pages/dir1/dir2/hello.html
https://interactive-examples.mdn.mozilla.net/pages/js/dir1/dir2/hello.html
https://interactive-examples.mdn.mozilla.net/pages/js/dir1/dir2/hello.html
https://interactive-examples.mdn.mozilla.net:1234/pages/js/dir1/dir2/hello.html

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接