【问题标题】:Why does window.history.back() jump back two states?为什么 window.history.back() 会跳回两个状态?
【发布时间】:2013-06-23 21:44:21
【问题描述】:

我一直在玩 window.history.pushState 和 onpopstate,但在我看来,按下返回会跳回两个状态,跳过一个。

查看https://developer.mozilla.org/en-US/docs/Web/API/window.onpopstate?redirectlocale=en-US&redirectslug=DOM%2Fwindow.onpopstate 示例:

window.onpopstate = function(event) {
  alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};

history.pushState({page: 1}, "title 1", "?page=1");
history.pushState({page: 2}, "title 2", "?page=2");
history.replaceState({page: 3}, "title 3", "?page=3");
history.back(); // alerts "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // alerts "location: http://example.com/example.html, state: null
history.go(2);  // alerts "location: http://example.com/example.html?page=3, state: {"page":3}

History.js 似乎表现出相同的行为。请参阅“直接使用 History.js”部分中的 https://github.com/browserstate/history.js。它在第二个 back() 中从状态 3 跳转到状态 1。

那么为什么它会有这种行为或者我错过了什么?

【问题讨论】:

    标签: javascript html history.js html5-history


    【解决方案1】:

    那是因为您在第三个示例中使用了replaceState

    replaceState 顾名思义就是替换当前状态。它不会添加新状态。

    所以在history.replaceState({page: 3}, "title 3", "?page=3"); 之后?page=2 在历史上是不存在的...


    引用The replaceState() method

    history.replaceState() 的操作与history.pushState() 完全相同,只是replaceState() 修改当前历史条目而不是创建新条目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 2010-09-28
      • 2015-09-09
      相关资源
      最近更新 更多