我的问题是,我想通过JavaScript重定向到上面的目录。

我的代码:

location.href = (location.href).substr(0, (location.href).lastIndexOf('folder'))

URL看起来是这样的:

example.com/path/folder/index.php ?文件= abc&test = 123 lol =酷

重定向的影响如下:

example.com/path/&test = 123 lol =酷

但要有这个:

example.com/path/

我该怎么做呢?


当前回答

这是一个老问题,但只是为了提供更多信息,这是url的工作原理:

window.location.href = 'https://domain/path';   // absolute
window.location.href = '//domain/path';         // relative to current schema
window.location.href = 'path';                  // relative to current path
window.location.href = '/path';                 // relative to domain
window.location.href = '../';                   // one level up

其他回答

你可以做一个相对重定向:

window.location.href = '../'; //one level up

or

window.location.href = '/path'; //relative to domain

< a href = " . .>没有JS需要</a>

. .表示父目录。

如果你使用位置。主机名你会得到你的domain.com部分。然后位置。Pathname会给你/path/folder。我会分割位置。pathname通过/和重新组装URL。但除非你需要查询字符串,你可以重定向到..转到上面的目录。

重定向到../

我试图将我当前的网站重定向到同一页面上的其他部分,使用JavaScript。以下代码为我工作:

location.href='/otherSection'