gpt4 book ai didi

javascript - window.popstate之后如何恢复原来的内容?

转载 作者:行者123 更新时间:2023-11-28 09:39:58 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com