0

这是我在 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);
    };
  }
});

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

在此处输入图像描述

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

4

1 回答 1

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);
    });
});
于 2013-04-12T10:55:27.210 回答