简体   繁体   中英

browser back button is not updating page

I'm setting the URL after the hashmark with a jquery click event. The URL is getting set properly but when I use the browsers back button it doesn't take me to the previous page.

Before my click event the URL looks like this:

http://example.com/menu.php?home

My click event looks like this:

$('#visits').click(function() { 
    $('#main').load("visits.php?type=1&view=1", function () { 
        location.href = "#visits";  
    });
    return false;
});

My URL now looks like this:

http://example.com/menu.php?home#visits

It seems as though menu.php doesn't get called with the browsers back button.

Any idea what I'm missing?

Use the onhashchange event of the window, to check if the hash changes. This is getting called when you hit the back Button of your browser.

$(window).bind('hashchange',function() {
    if (location.hash != '#visits') {
        //Code to revert the changes on the page
    }
}

Older versions of IE don't support hashchange, so you have to cheat by using setInterval to poll a few times a second and check if it's changed.

if($.browser.msie && $.browser.version < 7){
    setInterval(function(){
        if(window.location.hash != window.lastHash){
            hashChangeHandler();
            window.lastHash = window.location.hash;
        }
    }, 100);
}
else{
    $(window).bind('hashchange',function() {
        if (location.hash != '#visits') {
            hashChangeHandler();
        }
    }
}

You could code something like this:

var _hash = '';

function myHashChangeCallback(hash) {
    // handle hash change
    // load some page using ajax, etc
}

function hashCheck() {
    var hash = window.location.hash;
    if (hash != _hash) {
        _hash = hash;
        myHashChangeCallback(hash);
    }
}

setInterval(hashCheck, 100);

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