我的问题是我想通过 JavaScript 重定向到上面的目录。
我的代码:
location.href = (location.href).substr(0, (location.href).lastIndexOf('folder'))
URL 如下所示:
example.com/path/folder/index.php?file=abc&test=123&lol=cool
重定向只影响这个:
example.com/path/&test=123&lol=cool
但是想要这个:
example.com/path/
我该怎么做?
您可以进行相对重定向:
window.location.href = '../'; //one level up
或者
window.location.href = '/path'; //relative to domain
如果您使用 location.hostname
,您将获得 domain.com 部分。然后 location.pathname
将为您提供 /path/folder。我会用 / 拆分 location.pathname
并重新组合 URL。但除非您需要查询字符串,否则您只需重定向到 ..
即可转到上面的目录。
https://developer.mozilla.org/en-US/docs/Web/API/Location/assign
window.location.assign("../"); // 上一级
window.location.assign("/path"); // 相对于域
重定向到 ../
<a href="..">no JS needed</a>
..
表示父目录。
我正在尝试使用 JavaScript 将我当前的网站重定向到同一页面上的其他部分。以下代码对我有用:
location.href='/otherSection'
试试下面的js代码
位置 = '..'
window.location.replace
stackoverflow.com/questions/503093/…window.location.href
。当您想模拟 http 重定向(因此不生成历史项目)时,您应该只使用window.location.replace
。document.location
旨在作为只读属性。使用window.location
更安全。请参阅this question。window.location.href = '../'
重定向到站点的根目录,而不是像预期的那样“向上一级”。当当前页面是“www.example.com/customers/list”时,我需要使用'./'
。我猜这是因为“列表”不被视为目录级别。