window.location.hash

利用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.οnhashchange=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="" οnclick="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>


转载于:https://my.oschina.net/u/2618661/blog/630590

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值