如何使用window.open()快速访问我的网站的根目录

How to quick-access the root of my website using window.open()?

本文关键字:我的 访问 网站 根目录 window 何使用 open      更新时间:2023-09-26

假设我的网站中有一个页面:

  • mywebiste.com/section1/slideshow/main/example.html

我想使用window.open()访问我网站中的这些页面:

  • mywebsite.com/section2/index.html
  • mywebsite.com/section2/article1/gallery.html
  • mywebsite.com/login.php

这些只是随机示例,但我试图指出它们离example.html页面很远,我将不得不使用很多../,因此最终会得到很长(且令人困惑)的 URL。

我认为应该有一种方法可以直接访问网站的根目录,但仍然使用相对URL。(就像是否存在快捷方式.../root/,并且可以将您重定向到根目录)。

这可能吗?

只是用/开头应该可以。

window.open('/section2/index.html', ...); // etc

您可以在 JavaScript 中使用返回协议、主机名和端口的 window.location.origin

例如:

window.open(window.location.origin + '/other-folder/index.html');

这与IE不兼容,但您可以尝试以下polyfill:http://tosbourn.com/a-fix-for-window-location-origin-in-internet-explorer/