前进按钮在 history.pushState 后不起作用

Jos*_*son 7 html javascript ajax jquery pushstate

我已经找到了如何修复后退按钮,但前进按钮仍然无法修复。url 会改变,但页面不会重新加载,这就是我正在使用的:

$('.anchor .wrapper').css({
  'position': 'relative'
});

$('.slanted').css({
  'top': 0
});

// Do something after 1 second
$('.original-page').html('');
var href = '/mission.html'

console.log(href);
// $('#content-div').html('');

$('#content-div').load(href + ' #content-div');
$('html').scrollTop(0);
// loads content into a div with the ID content_div

// HISTORY.PUSHSTATE
history.pushState('', 'New URL: ' + href, href);
window.onpopstate = function(event) {
  location.reload();
};

//            response.headers['Vary'] = 'Accept';
//            window.onpopstate = function (event) {
//                alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
//                            location.reload();
//                        response.headers['Vary'] = 'Accept';
//            };

//            $(window).bind('popstate', function () {

//            window.onpopstate = function (event) {
//                window.location.href = window.location.href;
//                location.reload();
//            };

e.preventDefault();
Run Code Online (Sandbox Code Playgroud)

如您所见,我尝试了几种不同的方法,后退按钮工作正常,但前进按钮无效。

sst*_*ten 13

请记住,history.pushState()将新状态设置为最新的历史状态。并window.onpopstate在您设置的状态之间导航(向后/向前)时调用。

所以不要pushStatewindow.onpopstate被调用时,因为这会将新状态设置为最后一个状态,然后就没有什么可前进的了。

  • 这正是我所需要的。直到我阅读了这个答案,我才意识到我正在这样做。我必须将 `history.pushState` 调用与函数分开,这样我在使用 `window.onpopstate` 时就不会调用 `history.pushState`。 (4认同)