首页 文章

重定向到JavaScript中的相对URL

提问于
浏览
284

我有一个问题:我想通过JavaScript重定向到上面的目录 . 我的代码:

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

网址如下所示:

example.com/path/folder/index.php?file=abc&test=123&lol=cool

重定向会影响到这个:

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

但想拥有这个:

example.com/path/

我怎么能这样做?

6 回答

  • 8

    如果您使用 location.hostname ,您将获得domain.com部分 . 然后 location.pathname 会给你/ path /文件夹 . 我会通过/拆分 location.pathname 并重新组合URL . 但除非您需要查询字符串,否则您只需重定向到 .. 即可进入上面的目录 .

  • 5

    重定向到 ../

  • 0

    <a href="..">no JS needed</a>

    .. 表示父目录 .

  • 2

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

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

    要么

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

    https://developer.mozilla.org/en-US/docs/Web/API/Location/assign

    • window.location.assign("../"); //一级上升

    • window.location.assign("/path"); //相对于域名

  • 531

    我正在尝试使用JavaScript将我当前的网站重定向到同一页面上的其他部分 . 以下代码适用于我:

    location.href='/otherSection'
    

相关问题