1

以下代码继续将新 URL 推送到状态对象,同时动态更改页面内容。但是,当我开始按下Back按钮并返回原始页面时,不会显示原始内容,而是保留下一页的内容。我如何实现它?

<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
a = 0;
  $("p").click(function(){
var stateObj = { note : ++a };
history.pushState(stateObj, "page 2", "http://localhost/foo/"+a);
$(this).text(a);    
  });
  window.addEventListener('popstate', function(e){
  if (history.state){
    $("p").text(e.state.note);
if (location.href == 'http://localhost/hist.php') { $('p').text('If you click on me, I will disappear.'); }
   }
 }, false);
$("div").click(function() { alert(e.state.note); });
  });
</script>
</head>
<body>
<p>If you click on me, I will disappear.</p>
<div>Hi</div>
</body>
</html>
4

1 回答 1

1

It is your responsability to update the page content on popstate. The browser only handles the state.

I had an application, where I replace the main content of a page while navigation through an menu tree. I also updated the page title according to the new content.

When I just go back an forth in AJAX loaded pages, I can save the url to load in the StateObj. But on going back to the initial page, there is no state, and no saved title to restore.

I decided to reload the whole page, when I go back to the initial history state:

var doc_state={'title': ''};
var popped = ('state' in window.history && window.history.state !== null), initialURL = location.href;
function loadDocument(path,title){
    $('#document_area').html('<img src="spinner.gif" />');
    $('#document_area').load(path+'?ajax=true');
    document.title = title;
}

$(document).ready(function(){
    $('a.ajax_link').click(function(event){
        var path=$(this).attr('href');
        var title=$(this).text();
        doc_state['title']=title;
        event.preventDefault();
        loadDocument(path,title);
        window.history.pushState(doc_state,document.title,path);
    });
    $(window).bind('popstate', function(event){
        // Ignore inital popstate that some browsers fire on page load
        var initialPop = !popped && location.href == initialURL;
        popped = true;
        if ( initialPop ) return;

        var state = event.state;
        if (!state){
            state=history.state; // FF
        }

        if (state){
            var title= state.title;
            loadDocument(location.pathname, title);
        }
        else window.location.reload();

    });
}
于 2013-06-18T18:31:39.647 回答