jquery使用ajax时让其可跟踪历史前进和后退demo

2016-3-26 Jon js+jquery+ajax

写了一个demo使用ajax加载html页面,并且可以跟踪历史前进和后退


index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    .clearfix:before, .clearfix:after {display: table;content: " ";}
    .clearfix:after {clear: both;}
    .clearfix {*zoom: 1;}
    .lf {float: left;}
    .rf {float: right;}
    h1{padding:0;margin:0;font-size: 22px;line-height: 30px;}
    .main{width:1000px;margin:0 auto;line-height: 30px;padding:50px 20px;}
    .main .lf{width:220px;}
    .main .lf a{display: block;color:#4E9BD5;text-decoration: none;}
    .main .lf a.active,.main .lf a:hover{color:green;}
    .main .rf{width:700px;}
  </style>
</head>
<body>
  <div class="main">
    <div class="lf" id="item">
      <a href="#!h1" class="actve">我是h1</a>
      <a href="#!h2">我是h2</a>
      <a href="#!h3">我是h3</a>
      <a href="#!h4">我是h4</a>
      <a href="#!h5">我是h5</a>
    </div>
    <div class="rf" id="content">
      这是内容
    </div>
  </div>
  <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
  <script src="hashchange.js"></script>
</body>
</html>


hashchange.js

function setUser(_url){
  $.ajax({
    url: _url,
    type: "GET",
    success: function(data){
      $('#content').html(data);
    }
  });
}
$('#item a').click(function(){$(this).addClass('active').siblings().removeClass('active');});
function changeHashCallBack(){//hash变化之后,回调函数会被触发
  var hash = location.hash?location.hash:'#h1';
  var result = hash.substring(2);
  setUser(result+'.html');
}
if(document.all && !document.documentMode){
  /* 低于IE8的IE系列采用定时器监听 */
  setInterval(changeHashCallBack, 300);
}else{
  window.onhashchange = changeHashCallBack;
}
changeHashCallBack();


h1.html

<h1>我是h1</h1>


h2.html

<h1>我是h2</h1>
<h1>我是h2</h1>


h3.html

<h1>我是h3</h1>
<h1>我是h3</h1>
<h1>我是h3</h1>


h4.html

<h1>我是h4</h1>
<h1>我是h4</h1>
<h1>我是h4</h1>
<h1>我是h4</h1>


h5.html

<h1>我是h5</h1>
<h1>我是h5</h1>
<h1>我是h5</h1>
<h1>我是h5</h1>
<h1>我是h5</h1>


标签: ajax onhashchange

分享这篇文章
赞助鼓励:如果觉得内容对您有所帮助,您可以支付宝(左)或微信(右):

声明:如无特殊注明,所有博客文章版权皆属于作者,转载使用时请注明出处。谢谢!

发表评论:

皖ICP备15010162号-1 ©2015-2022 知向前端
qq:1614245331 邮箱:13515678147@163.com Powered by emlog sitemap