【问题标题】:How to restore original content after window.popstate?window.popstate 后如何恢复原始内容?
【发布时间】:2012-09-14 07:09:51
【问题描述】:

以下代码继续将新 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>

【问题讨论】:

    标签: javascript jquery html html5-history


    【解决方案1】:

    您有责任更新popstate 上的页面内容。浏览器只处理状态。

    我有一个应用程序,可以在导航菜单树时替换页面的主要内容。我也根据新内容更新了页面标题。

    当我在 AJAX 加载的页面中前后返回时,我可以将要加载的 url 保存在 StateObj 中。但是在回到初始页面时,没有状态,也没有保存的标题要恢复。

    当我回到初始历史状态时,我决定重新加载整个页面:

    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();
    
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-09
      • 2019-05-22
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 2014-09-06
      • 2020-05-08
      • 1970-01-01
      相关资源
      最近更新 更多