gpt4 book ai didi

javascript - 为什么 window.history.back() 会跳回两个状态?

转载 作者:行者123 更新时间:2023-11-28 20:26:38 25 4
gpt4 key购买 nike

我一直在使用 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 似乎显示了相同的行为。请参阅https://github.com/browserstate/history.js在“直接使用 History.js”部分。它在第二个 back() 中从状态 3 跳转到状态 1。

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

最佳答案

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

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

因此,在 history.replaceState({page: 3}, "title 3", "?page=3"); 之后,?page=2 就这样做了历史上不存在...

<小时/>

引用The replaceState() method

history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one.

关于javascript - 为什么 window.history.back() 会跳回两个状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17265637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com