码迷,mamicode.com
首页 > Web开发 > 详细

html5 history实现无刷新页面

时间:2015-06-08 19:03:12      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

注:要在服务器下运行

<body>
<a href="test1.html" class="history">点击我跳到test1.html页面</a>
<a href="index1.html" class="history">点击我跳到index1.html页面</a>
<a href="hello.html" class="history">点击我跳到hello.html页面</a>
<p>以下是存放会更改的内容</p>
<div id="content"> </div>

<script type="text/javascript">
$(function(){

$(‘.history‘).on(‘click‘, function(e){
//此方法通知web服务器不执行相关联的方法
e.preventDefault();
var href = $(this).attr(‘href‘);
// 获取href
getContent(href, true);
});

});

//监听pushstate() popstate事件对象的state属性包含了这个历史记录条目的state对象的一个拷贝.
window.addEventListener("popstate", function(e) {

//使用e.state获取状态值
getContent(location.pathname, false);//若为true 则只改变路径不改变内容
});

function getContent(url, a) {
//获取路径
$.get(url)
//.done(funcyion())执行第二个回调函数 .done是 deferred对象 是jq回调函数的解决方案
.done(function( data ) {

// 更改内容
$(‘#content‘).html(data);

if(a == true) {
//增加历史记录
history.pushState(null, null, url);
}

});
}

</body>

html5 history实现无刷新页面

标签:

原文地址:http://www.cnblogs.com/ss977/p/4561369.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!