历史 Pushstate 和 Popstate 无法正常工作

History Pushstate and Popstate not working properly

$( document ).ready(function() {
    $(".a-menu").click(function(event){
        event.preventDefault();
        window.history.pushState({ content: $('.page-content').html() }, 
        pageData['header'], $(this).attr('href'));
    });

    window.onpopstate = function(event){
        var d = event.state;
        $('.page-content').html(d.content); //d.content doesn't give anything for last back attempt.
    };
});

以及我应该为条件做些什么,比如我回去然后继续前进。

注意:我在Whosebug上看到了很多答案,我知道这可能是重复的,我已经尝试了很多解决方案。

解决代码后...我达到了这个

$( document ).ready(function() {
     var getHtml = $('.page-content').html();
     $(".a-menu").click(function(event){
        event.preventDefault();
        var ThisHref = $(this).attr('href');
        getHtml = $('.page-content').html();

        // add A new Content 
        $('.page-content').html('<div>'+ThisHref+'</div>');

        if(window.location.href.indexOf(ThisHref) === -1){
           window.history.pushState({content: $('.page-content').html()},null, ThisHref);
        }
    });
    window.addEventListener('popstate', function(event) {
       var state = event.state == null ? getHtml : event.state.content;
       console.log(state);
       $('.page-content').html(state);        
    });
});

这正是它应该如何工作的

$( document ).ready(function() {
  var getHtml = $('.page-content').html();   // get the content div html content
  $(".a-menu").click(function(event){        // <a> click event
      event.preventDefault();                //prevent redirect
      var ThisHref = $(this).attr('href');   // get this <a> href attribute
      getHtml = $('.page-content').html();   // get the content div html content before change the content

      // add A new Content 
      $('.page-content').html('<div>Current page is: '+ThisHref+'</div>');

      if(window.location.href.indexOf(ThisHref) === -1){ // check if url dont have a href to prevent run the pushState in each click
        window.history.pushState({content: $('.page-content').html()},null, ThisHref);  // pushState
      }
  });
window.addEventListener('popstate', function(event) {
    var state = event.state == null ? getHtml : event.state.content; // if event.state == null get the previous html  if not get the content
    //console.log(state);
    $('.page-content').html(state); // append the html to the content div

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="index.html" class="a-menu">Home</a>
<a href="Cat.html" class="a-menu">Cat Page</a>
<a href="Dog.html" class="a-menu">Dog Page</a>
<div class="page-content"><div>Current page is: index.html</div></div>

你也可以看看this fiddle

试试这个

window.onpopstate = function(){
    window.history.go(-1);
    var d = history.state;
    $('.page-content').html(d);
};