下面的代码继续将新的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>
最佳答案
您有责任更新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();
});
}
关于javascript - window.popstate之后如何还原原始内容?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12537683/