在上一篇文章中介绍history.pushState()的时候,我们提到location.hash存在的3个问题。第一个问题:url会发生改变,这个很容易理解。现在我们看下第二个问题和第三个问题,即如何修改浏览器的历史记录,如何让历史记录存储更多状态相关的信息。状态相关的信息上一篇博客其实已经很容易看出来了,history.pushState()的第一个参数是javascript对象,我们当然可以在这个对象中存放任何我们想要的数据。本文我们主要看一下,如何利用histroy.replaceState修改浏览数的历史记录。
还是上一篇文章中的例子,假如我们要实现这样的功能:在当前页面显示这个页面被访问的次数。很显然通过浏览器的前进和后退按钮,我们可以无限多次地访问某个页面。但是我们并不希望产生更多的历史记录,因为我在A页面和B页面之前跳过来跳过去,说白了就是2个历史记录,只不过页面信息有变化而已。通过pushState和location.hash是无法达到这个要求的,因为这2种方式都是产生新的历史记录,无法修改已有的历史记录。这个时候replaceState就排上用场了。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
var currentPageIndex = 0;
window.onload = function(){
currentPageIndex = 0;
showPageAtIndex(currentPageIndex,1);
addHistory(currentPageIndex);
}
// onpopstate可以监控state变化
window.onpopstate = function(e){
if(history.state)
{
var state = history.state;
var count = 1 + state.visitTime;
showPageAtIndex(state.id,count);
// 修改当前状态信息(修改历史记录)
history.replaceState({"id":state.id,"visitTime":count},"","");
}
}
function toNextPageWhenClick()
{
currentPageIndex++;
if(isValidPageIndex(currentPageIndex))
{
showPageAtIndex(currentPageIndex, 1);
addHistory(currentPageIndex);
}
else
{
return;
}
}
function showPageAtIndex(id,count)
{
$("div[id!="+id+"]").hide();
$("#"+id).show();
if(isHomePage(id))
{
$("input").attr("value","current is home page,next page=1");
}
else if(isLastPage(id))
{
$("input").attr("value","current page="+id+", it is the end.");
}
else
{
$("input").attr("value","current page="+id+",next page="+(id+1));
}
$("#"+id).find("span").text(count);
}
function isValidPageIndex(id)
{
return id <= 5;
}
function isLastPage(id)
{
return id == 5;
}
function isHomePage(id)
{
return id == 0;
}
// 增加历史记录
function addHistory(id)
{
history.pushState({"id":id,"visitTime":1},"","");
}
</script>
<style>
.navigate{
height:100px;
width:300px;
background-color:#0000ff;
display:none;
}
.home{
height:100px;
width:300px;
background-color:#00ff00;
display:none;
}
.last{
height:100px;
width:300px;
background-color:#ff0000;
display:none;
}
</style>
</head>
<body>
<input type="button" value="" onclick="toNextPageWhenClick();">
<div class="home" id="0">HOME PAGE.this is <span></span> time to visit this page.</div>
<div class="navigate" id="1">ajax1.this is <span></span> time to visit this page.</div>
<div class="navigate" id="2">ajax2.this is <span></span> time to visit this page.</div>
<div class="navigate" id="3">ajax3.this is <span></span> time to visit this page.</div>
<div class="navigate" id="4">ajax4.this is <span></span> time to visit this page.</div>
<div class="last" id="5">last page.this is <span></span> time to visit this page.</div>
</body>
</html>
在onpopstate事件处理函数中,我们拿到了当前历史记录的状态信息,之后再用replaceState修改状态信息。就这样,我们修改了状态信息(修改了历史记录),但是并没有产生新的记录。这是用pushState和location.hash无法实现的。