【问题标题】:history.pushstate fails browser back and forward buttonhistory.pushstate 使浏览器后退和前进按钮失败
【发布时间】:2014-05-10 04:03:45
【问题描述】:

我正在使用 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();
        });
    });
});

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

在克莱顿的回答的帮助下更新了脚本

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'));
});

【问题讨论】:

    标签: javascript jquery browser-history pushstate


    【解决方案1】:

    @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'));
        });
    
     });
    

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

    【讨论】:

    • 非常感谢克莱顿!您的示例非常具有说明性,现在这一切都说得通了。我将更新我的问题以显示我的最终代码是什么样的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多