之前问过好几个做Java后台的朋友,他们一般处理分页是后台处理好分页返回数据给前台的,都没用过jQuery分页。
然而由于需求问题。需要把数据存放在application中返回到前台,之后再进行分页。所以上网搜索了一下jQuery分页代码,不能满足需求。所以自己弄了一个,和大家分享一下。
效果图是这样的:
下面是Javascrip代码和对应的部分html代码
效果图是这样的:
下面是Javascrip代码和对应的部分html代码
- <script type= "text/javascript" >
- $ (document). ready(function(){
- $ (".items .wrap:gt(1)").hide ();//初始化,前面4条数据显示,其他的数据隐藏。
- var total_q= $(".items .wrap" ).index()+ 1;//总数据
- var current_page= 2;//每页显示的数据
- var current_num= 1;//当前页数
- var total_page= Math.round(total_q/current_page) ;//总页数
- var next= $(".next" );//下一页
- var prev= $(".prev" );//上一页
- $ (".total"). text(total_page); //显示总页数
- $ (".currentPage").text (current_num);//当前的页数
- for( var i=1 ;i<=total_page; i++){
- if(i== 1){
- $( ".next").before (" <a href='javascript:;' class='otherPage currentPage'>"+i+ "</a>");
- } else{
- $ (".next"). before(" <a href='javascript:;' class='otherPage'>"+i+ "</a>");
- }
- }
- //点击数字页
- $ (".otherPage").click( function(){
- current_num=$( this).text ();//当前的页数
- $( ".currentPage" ).removeClass( "currentPage" )
- $( this).addClass ("currentPage"); //点击下一页的时候就取消样式,下一个添加样式
- $. each($ ('.items .wrap') ,function(index ,item){
- var start = current_page* (current_num- 1); //起始范围
- var end = current_page * (current_num) ;//结束范围
- if(index >= start && index < end){ //如果索引值是在start和end之间的元素就显示,否则就隐
- $(this). show();
- }else {
- $(this). hide();
- }
- });
- }) ;
- //下一页
- $ (".next").click( function(){
- current_num=$( ".currentPage" ).text() ;//当前的页数
- if(current_num==total_page){
- return false; //如果大于总页数就禁用下一页
- }
- else{
- $(".currentPage" ).removeClass( "currentPage" ).next(). addClass("currentPage" );//点击下一页的时候就取消样式,下一个添加样式
- $. each($ ('.items .wrap') ,function(index ,item){
- var start = current_page* (current_num) ;//起始范围
- var end = current_page * (current_num* 1+1 );//结束范围
- if(index >= start && index < end){ //如果索引值是在start和end之间的元素就显示,否则就隐
- $(this). show();
- }else {
- $(this). hide();
- }
- });
- }
- });
- //上一页方法
- $ (".prev").click( function(){
- current_num=$( ".currentPage" ).text() ;//当前的页数
- if(current_num== 1){
- return false;
- } else{
- $(".currentPage" ).removeClass( "currentPage" ).prev(). addClass("currentPage" );
- $. each($ ('.items .wrap') ,function(index ,item){
- var start = current_page* (current_num- 2); //起始范围
- var end = current_page * (current_num- 1); //结束范围
- if(index >= start && index < end){ //如果索引值是在start和end之间的元素就显示,否则就隐藏
- $(this). show();
- }else {
- $(this). hide();
- }
- });
- }
- })
- })
- </script>
- <div class= "items">
- <div class= "wrap">
- <div class="item-title" ><!--编写需要分页的内容--></div>
- </div>
- </div>
- <div class= "pageIndex" >
- <!-- 分页导航 currentPage:当前页 -->
- <div class="nav-btn">
- <a href="#" class="prev" > 上一页 </a>
- <a href="#" class="next"> 下一页 </a>
- </div>
- </div>