gpt4 book ai didi

javascript - 单击后退按钮时如何返回到之前的状态

转载 作者:行者123 更新时间:2023-11-28 05:33:30 25 4
gpt4 key购买 nike

我正在使用 history.pushState 通过 ajax 请求更改页面内容。

并且可以肯定的是,在 history.pushState 之后,浏览器中的前进按钮将被禁用,因此肯定会单击的任何按钮都将成为后退按钮。

所以我想回到pushState之前的页面主状态。我使用ajax请求来检索主状态的内容,但问题是如何使浏览器中的url返回到主url。由于一些问题,我不想为此使用 PushState 方法

在其他ajax成功后,我将值加一,以了解我的pushState有多远。

var mainState;
var pushed = false;
$('a').click(function(){
$.ajax({
url: "/path/to/content",
success: function(data){
$('div').html(data);
history.pushState('state', 'title', 'url');
mainState ++;
pushed = true;
}
})
})

window.onpopstate(function(){
if(pushed){ //knowing fully well that the forward button is disabled
// take it back to the main state
history.go(-mainState);
}
})

假设 mainState 为 3,我单击后退按钮而不是转到 mainState,它会将我带到 mainState - 3。

请问有人知道我可以做到这一点吗?

最佳答案

var mainState = 3;
-mainState; //-3
--mainState; //2

你的代码应该是这样的

window.onpopstate(function(){
if(pushed){
history.go(--mainState); //FIXED
}
})

关于javascript - 单击后退按钮时如何返回到之前的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39528120/

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