简体   繁体   中英

history.pushState with back and forward buttons

I need to make back and forward buttons working with this ajax method
This code working good and the URL on browser changing as it should be
but when you click on back and forward buttons, nothing happening

(function(){

    function clickNav(e){
        e.preventDefault();
        var href = $(this).attr('href');
        history.pushState(null, null, href);

        $.ajax({
            url: href,
            dataType: 'html',
            cache: false
        }).done(function(html){
            var $html = $(html);

            $('title').html($html.filter('title').text());
            $('#content').replaceWith($html.find('#content'));
            $('#nav').replaceWith($html.find('#nav'));

            $('#nav li a').on('click',clickNav);
        });

    }
    $('#nav li a').on('click',clickNav);

})();

I had to deal with this today. The following works for me (tested on four browsers in Win 7 so far)...

//CHECK FOR ADDRESS BAR CHANGE EVERY 500ms
var wwcint = window.setInterval(function(){
    if(window.last_location_href == undefined) {
        window.last_location_href = document.location.href;
    } else if(window.last_location_href != document.location.href) {
        window.last_location_href = document.location.href;

        //DO WHATEVER YOU NEED TO DO TO LOAD THE CORRECT CONTENT
        someFunctionToLoadTheContent(document.location.href);
    }
}, 500);

it is because your history is empty. For this you need to use

 history.pushState();

After that my buttons start working

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM