【问题标题】:How can I go back to the previous state when back button is clicked单击后退按钮时如何回到以前的状态
【发布时间】:2016-09-16 09:32:33
【问题描述】:

我正在使用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。

请问有人知道我能做到吗?

【问题讨论】:

    标签: javascript history pushstate


    【解决方案1】:
    var mainState = 3;
    -mainState; //-3
    --mainState; //2 
    

    您的代码应如下所示

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 2017-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多