【问题标题】:Regarding using History.js to manage browser state关于使用 History.js 管理浏览器状态
【发布时间】:2015-12-31 18:09:59
【问题描述】:
History.pushState(data,title,url)

History.pushState({state:1}, "State 1", "?state=1")

假设如果我需要存储页码和排序顺序,那么我需要编写什么代码?

url 部分是强制性的?

当用户点击浏览器后退或前进按钮时如何恢复状态?

假设我有一个这样的对象

var PageState= {
    PageNo:1,
    SortCol:"Name",
    SortOrder:"ASC"
};

我可以这样保存吗

History.pushState({state:PageState}, null, null); ?

当用户单击浏览器后退和前进按钮时,我如何使用 History.js lib 从浏览器历史记录中取回状态?

寻找代码示例。谢谢

【问题讨论】:

    标签: jquery browser-history history.js


    【解决方案1】:

    URL 参数是必需的,因为它会附加到地址栏中的基本 URL。如果您想保持在同一路径上,但要保存新的历史状态,则可以使用当前 url:History.pushState(state, null, location.href)

    当历史状态改变时,窗口会发出一个事件。

    var PageState = {
        PageNo: 1,
        SortCol: "Name",
        SortOrder: "ASC"
    };
    
    History.pushState(PageState, null, location.href);
    
    stateChangeHandler = function(event) {
        // This PageState is the same object defined above
        var PageState = event.state;
        var NewLocation = event.target.location.href;
    };
    
    // These two statements are nearly equivalent. Only one is needed.
    window.onpopstate = stateChangeHandler;
    window.addEventListener("popstate", stateChangeHandler);
    

    延伸阅读:MDN popstate reference

    【讨论】:

      猜你喜欢
      • 2015-10-14
      • 1970-01-01
      • 2016-05-30
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多