作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
以下代码继续将新的 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/
如何使用 Blazor 在 Linux 平台下运行 Desktop 程序 本文将讲解如何使用 Blazor 运行跨平台应用,应用到的技术有以下几点 Blazor
低并发的友友们好,我是闪客。 Lambda 表达式非常方便,在项目中一般在 stream 编程中用的比较多。 List<Student> studen
我是一名优秀的程序员,十分优秀!