利用ajax局部刷新页面
利用window.location.hash记录刷新内容:
如果location.hash发生了变化,则浏览器地址栏的URL也会发生变化,而浏览器会产生一个历史纪录。
如果location.hash发生变化,则会触发window的hashChange事件,我们可以处理这个事件。
<!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);
recordHash(currentPageIndex);
}
// onhashchange可以监控hash变化
window.onhashchange=function(){
var hash = window.location.hash;
var id = parseInt(hash.substr(1));
showPageAtIndex(id);
};
function toNextPageWhenClick()
{
currentPageIndex++;
if(isValidPageIndex(currentPageIndex))
{
showPageAtIndex(currentPageIndex);
recordHash(currentPageIndex);
}
else
{
return;
}
}
function showPageAtIndex(id)
{
$("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));
}
}
function isValidPageIndex(id)
{
return id <= 5;
}
function isLastPage(id)
{
return id == 5;
}
function isHomePage(id)
{
return id == 0;
}
// hash改变,浏览器会自动生成一个历史记录
function recordHash(id)
{
window.location.hash=id;
}
</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</div>
<div class="navigate" id="1">ajax1</div>
<div class="navigate" id="2">ajax2</div>
<div class="navigate" id="3">ajax3</div>
<div class="navigate" id="4">ajax4</div>
<div class="last" id="5">last page</div>
</body>
</html>