【问题标题】:history.pushState() and clicking back/forward buttonhistory.pushState() 并单击后退/前进按钮
【发布时间】:2013-04-12 06:59:11
【问题描述】:

这是我在 ajax 加载时更改 url 的代码

$.ajax({
  url: url,
  success: function (data) {
  $(selector).html(data);
    var title = data.match("<title>(.*?)</title>")[1]; // get title of loaded content   
    window.history.pushState( {page : 0} , document.title, window.location.href ); // store current url.    
    window.history.pushState( {page : 1} , title, url ); // Change url.
    document.title = title; // Since title is not changing with window.history.pushState(), 
    //manually change title. Possible bug with browsers.
    window.onpopstate = function (e) {
        window.history.go(0);
    };
  }
});

当我点击 back 时,上一页正在加载。如果我再次点击没有任何反应。再点击一下它就会转到第一页。经过一些测试,我发现,在每个 ajax 加载时,后退按钮都有 2 个相同的页面

我还需要一个代码来获取点击前进按钮时的历史记录

【问题讨论】:

    标签: jquery html pushstate html5-history


    【解决方案1】:

    版主删除了我的帖子,因为我确实提供了一些代码片段来提供帮助。


    但我还是会尝试举个例子:

    假设你有这段代码是由onclick事件触发的。

    $(function() {
        function load(url, push) {
            $.ajax({
                url: url,
                success: function (data) {
                    var title = data.match("<title>(.*?)</title>")[1];
                    document.title = title;
                    if (push) {
                        history.pushState(null, title, url);
                    }
                }
            });
        }
    
        $(document).click(function(e) {
            if (e.target.nodeName === 'A') {
                var url = $(e.target).attr('href');
                if (url.indexOf('#') !== 0) {
                    load(url, true);
                    e.preventDefault();
                }
            }
        });
    
        $(window).bind('popstate', function(e) {
            load(window.location.href, false);
        });
    });
    

    【讨论】:

    • 如果你能解释一下这段代码的用途;(
    猜你喜欢
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    相关资源
    最近更新 更多