首页 文章

如何处理带有内容更改的history.pushState

提问于
浏览
1

虽然Mozilla在 history.pushStatehistory.replaceState 上有一个easy to understand documentation,但是当按下后退按钮并动态更改内容时,它没有告诉我如何处理内容 .

假设foo.html有一个表单并执行一个AJAX调用来替换提交时的内容,那么pushState如下所示:

history.pushState({content:$('#content').html()}, '', 'bar.html');

当用户单击后退按钮时,URL会更改回foo.html,但页面不会显示该表单 . 我该如何显示表格?我看了一下popState但是无法让它正常工作 .

2 回答

  • 1

    您需要存储重新呈现旧内容所需的所有状态,然后使用该状态在 popstate 上重新创建上一页 .

    诸如Knockout.js(或完整的MVC框架)之类的模型绑定技术可以使这更容易 .

  • 1

    所以这就是我为解决它而做的事情:

    当foo.html加载时,我执行 history.replaceState({container:$(#container').html()},'', window.location);

    然后在ajax调用替换内容后,我执行此操作: history.pushState({container:$(#container').html()},'', 'bar.html');

    在页面加载时,我绑定popstate以检查事件是否具有包含容器的状态对象,如下所示:

    $(window).bind("popstate", function(event) {
        if (event.state != null){
            if ('container' in event.state){
                $(#container').html(event.state.container);
            }
        }
    });
    

相关问题