【问题标题】:history.pushState how can I get rid of get parameters?history.pushState 我怎样才能摆脱获取参数?
【发布时间】:2014-11-19 10:35:57
【问题描述】:

我正在使用

  history.pushState('id','myTitle','myURL');

操作显示的 URL 和历史堆栈。 在某些时候,我正在推动 get 参数,如下所示:

history.pushState('id','myTitle','?mySubLinkedStuff=hotSubLinkedStuff');

当我这样做的时候

history.pushState('id','myTitle','#justSomeHashtag');

它产生http://example.com?mySubLinkedStuff=hotSubLinkedStuff#justSomeHashtag 我也可以覆盖 mySubLinkedStuff 的值,但似乎无法完全摆脱它。

想要的结果:

http://example.com#justSomeHashtaghttp://example.com/#justSomeHashtag

显然我不想在服务器上进行整个往返,我也想避免使用绝对路径或 URL 来保持项目的可移植性。

【问题讨论】:

  • history.pushState('id','title','http://example.com/#hash')不行吗?
  • 应该提到,由于项目可移植性,我想避免使用绝对寻址。但你是对的 - 绝对 URL 当然可以。问题已编辑。
  • '/#hash' 怎么样?

标签: javascript html browser-history pushstate


【解决方案1】:

正如 NimrodArgov 所说的那样:覆盖现有的 get-parameter 字符串如果您 推送完整的 URL。 因此,为了确保应用程序的可移植性(使其可在各种域中使用),我这样做了:

history.statePush(document.location.origin + window.location.pathname + '#myHashValue');

运行良好且快速。

【讨论】:

    【解决方案2】:

    不带 GET 参数推送当前地址:

    history.pushState("id", "myTitle", 
      location.protocol + "//" + location.host +
      location.pathname + location.hash
    );
    

    除此之外;

    要推动 散列 更改,我可以做:

    history.pushState("id", "myTitle", 
      location.protocol + "//" + location.host +
      location.pathname + location.search + "#myHashHere"
    );
    

    要推送 查询 更改,我可以这样做:

    history.pushState("id", "myTitle", 
      location.protocol + "//" + location.host +
      location.pathname + "?my=query&over=here" + location.hash
    );
    

    ※ 对不起,我没有足够的业力来评论Max’s answer...:/

    【讨论】:

      猜你喜欢
      • 2012-12-26
      • 1970-01-01
      • 2021-01-27
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2022-12-18
      • 1970-01-01
      相关资源
      最近更新 更多