javascript - history.pushstate 使浏览器后退和前进按钮失败

标签 javascript jquery browser-history pushstate

我正在使用 jQuery 动态加载 div 容器中的内容。

服务器端代码检测请求是 AJAX 还是 GET。

我希望浏览器的后退/前进按钮与代码一起工作,所以我尝试使用 history.pushState。我必须执行以下代码:

$('.ajax').on('click', function(e) {
    e.preventDefault();
    $this = $(this);
    $('#ajaxContent').fadeOut(function() {
        $('.pageLoad').show();
        $('#ajaxContent').html('');
        $('#ajaxContent').load($this.attr('href'), function() {
            window.history.pushState(null,"", $this.attr('href'));
            $('.pageLoad').hide();
            $('#ajaxContent').fadeIn();
        });
    });
});

一切正常,除了使用浏览器的后退/前进按钮浏览时,栏中的地址会按计划更改但页面不会更改。我做错了什么?

在 Clayton 的回答的帮助下更新了脚本

var fnLoadPage = function(url) {
    $('#ajaxContent').fadeOut(function() {
        $('.pageLoad').show();
        $('#ajaxContent').html('').load(url, function() {
            $('.pageLoad').hide();
            $('#ajaxContent').fadeIn();
        });
     });
};

window.onpopstate = function(e) {
     fnLoadPage.call(undefined, document.location.href);
};

$(document).on('click', '.ajax', function(e) {
    $this = $(this);
    e.preventDefault();
    window.history.pushState({state: new Date().getTime()}, '', $this.attr('href'));
    fnLoadPage.call(undefined, $this.attr('href'));
});

最佳答案

@Barry_127,看看这是否适合你:http://jsfiddle.net/SX4Qh/

$(document).ready(function(){
    window.onpopstate =  function(event) {
        alert('popstate fired');
        $('#ajaxContent').fadeOut(function() {
            $('.pageLoad').show();
            $('#ajaxContent').html('')
                             .load($(this).attr('href'), function() {
                                $('.pageLoad').hide();
                                $('#ajaxContent').fadeIn();
                             });
        });
    };

    $('.ajax').on('click', function(event) {
        event.preventDefault();
        alert('pushstate fired');
        window.history.pushState({state:'new'},'', $(this).attr('href'));
    });

 });

如果您查看我提供的 fiddle 并单击按钮,将触发警报,表明您正在推送一个新状态。如果您在 pushstate 触发后继续单击后退按钮,您将看到前一个页面(或 popstate)将触发。

关于javascript - history.pushstate 使浏览器后退和前进按钮失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22751023/

相关文章:

javascript - jquery:将一组元素粘贴到另一组元素/合并元素上

javascript - 将 diffrenet href 添加到 cytoscape.js 中的某些节点

javascript - 显示 API 结果的最简单方法

jquery - 从数组值旋转 jquery ui spinner

javascript - 更改 window.location.hash 在历史记录中创建条目但不影响 chrome 后退按钮

ember.js - EmberJS : how to know if route was called because the user clicked the Back button

javascript - OPTIONS 在 REST API 调用之前调用元数据

javascript - 向对象添加属性的函数

javascript - 是否可以在父元素中找到文本并将其包装起来?

webview - Electron 极限历史记录goBack在Webview中