【问题标题】:window.location.href redirection not working with # in the urlwindow.location.href 重定向不适用于 url 中的 #
【发布时间】:2021-10-10 08:13:28
【问题描述】:

如果 url 包含“#”,为什么 window.loaction.href 不会重新加载页面。 控制台中的window.location.href = window.location.href 将重新加载页面,但window.location.href = window.location.href + "#abc" 将仅替换 url 而无需重新加载。

【问题讨论】:

  • 为什么要这样重新加载页面?当您有另一种单独的方法来实现这一点时?
  • location.href 不会重新加载页面,直到它识别出任何 url 更改并且 #param 似乎不符合更改的条件。添加 "?param" 似乎有效

标签: javascript location


【解决方案1】:

如果 URL 中有锚点 (#),window.location.href = window.location.href 不会重新加载页面,它的行为与 <a href="#abc> 标记相同。

还有window.open(window.location.href + "#abc","_self")不会刷新页面。

这也行不通:

window.location.href = window.location.href + "#rr";
window.reload();

还有window.location.replace( window.location.href + "#abc"); 也不行。

显然这是<a href="#abc#>标签中的标准行为。

【讨论】:

    【解决方案2】:

    为了在 javascript 中重新加载页面,您可以简单地使用

    window.location.reload()
    

    【讨论】:

      【解决方案3】:

      如果您想导航到同一页面上的锚点,您可以使用

      window.location.hash = "#abc";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-02
        • 1970-01-01
        • 1970-01-01
        • 2013-03-23
        • 2012-12-19
        • 1970-01-01
        • 2015-12-30
        • 2020-05-08
        相关资源
        最近更新 更多