2012-09-21 2 views
1

다음 코드는 새로운 URL을 상태 객체에 푸시하면서 페이지의 내용도 동적으로 변경합니다. 그러나 버튼을 눌러 원래 페이지로 돌아 가면 원본 콘텐츠가 표시되지 않고 대신 다음 페이지의 콘텐츠가 유지됩니다. 그것을 어떻게 성취합니까?window.popstate 이후 원본 콘텐츠를 복원하는 방법은 무엇입니까?

<!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> 

답변

0

페이지 내용을 popstate으로 업데이트하는 것은 사용자의 책임입니다. 브라우저는 상태 만 처리합니다.

메뉴 트리를 탐색하는 동안 페이지의 기본 콘텐츠를 바꿀 수있는 응용 프로그램이 있습니다. 나는 또한 새로운 내용에 따라 페이지 제목을 업데이트했다.

AJAX가로드 된 페이지로 돌아가려면 StateObj에로드 할 URL을 저장할 수 있습니다. 그러나 초기 페이지로 돌아 가면 상태가없고 복원 된 제목이 없습니다.

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

    }); 
} 
:

는 내가 초기 역사의 상태로 되돌아 갈 때, 전체 페이지를 다시로드하기로 결정
관련 문제