栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

JavaScript实现前端分页控件

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript实现前端分页控件

       现在web注重用户体验与交互性,ajax 提交数据的方式很早就流行了,它能够在不刷新网页的情况下局部刷新数据。前端分页多是用ajax请求数据(其他方式也有比如手动构造表单模拟提交事件等)。通过js将查询参数构造好发向后台,后台处理后以特定的格式返回,多为json,比较流行处理起来也很方便。当后台数据到达后,浏览器重新渲染界面当然也包括js分页控件,如果觉得每次绘制分页控件对前端性能有影响也可以不绘制,但实现起来相对麻烦。

       本人写的分页控件参考了其他网友的代码,链接忘了,控件接受四个参数或一个对象,其实是一样的对于后者只不过将四个参数放在一个对象中。pIndex:每次请求的页码,pSize:每次请求的页容量,container: 放分页控件的容器,fn:如何向服务器请求数据

       代码中主要用到了闭包,将上一次的请求信息保存起来,以备下次使用,虽然代码可以直接拿来用但是样式不是通用的,需要每次调样式还好样式比较简单。

function pagination(obj){
    
    if(!obj||typeof obj!="object"){
 return false;
    }
    var pageIndex= obj.pageIndex||1,
      pageSize=obj.pageSize||10,
      count= obj.count||0,
      container= obj.container,
      callback=obj.fn||function(){};
    var pageCount =Math.ceil(count/pageSize); 
    if(pageCount==0){
 return false ;
    }  
    if(pageCountul>.pg-prev").unbind("click").bind("click",function(){
  if(pageIndex <=1){
  return false ;
  }
  if(typeof callback=="function"){
  pageIndex--;
  pageIndex = pageIndex<1?1:pageIndex;
  obj.pageIndex= pageIndex;
  callback(pageIndex);
  pagination(obj);
  }
  });
 //下一页事件
 $(container).find(">ul>.pg-next").unbind("click").bind("click",function(){
  if(pageIndex ==pageCount){
  return false ;
  }
  if(typeof callback=="function"){
  pageIndex++;
  pageIndex =pageIndex >pageCount?pageCount:pageIndex;
  obj.pageIndex= pageIndex;
  callback(pageIndex);
  pagination(obj);
  }
  });
 $(container).find(">ul>li:not(.pg-more):not(.pg-prev):not(.pg-next)").unbind("click").bind("click",function(){
  pageIndex= +$(this).html();
  pageIndex = isNaN(pageIndex)?1:pageIndex;
  obj.pageIndex= pageIndex;
  if(typeof callback=="function"){
  callback(pageIndex);
  pagination(obj);
  }
  });
    };

    
    function printHead(){
 var html=[];
 html.push('
  • 上一页
  • '); return html.join(""); } function printBody(){ var html=[]; var render=function(num,start){ start=start||1; for(var i=start;i<=num;i++){ html.push('
  • '+i+'
  • '); } } if(pageCount<=7){ render(pageCount); }else{ if(pageIndex <4){ render(4); html.push('
  • ...
  • '); html.push('
  • '+pageCount+'
  • '); }else{ html.push('
  • 1
  • '); html.push('
  • ...
  • '); if(pageCount-pageIndex>3){ render(pageIndex+1,pageIndex-1); html.push('
  • ...
  • '); html.push('
  • '+pageCount+'
  • '); }else{ render(pageCount,pageCount-3); } } } return html.join(""); } function printTail(){ var html=[]; html.push('
  • 下一页
  • '); return html.join(""); } function show(){ container.innerHTML= '
      '+printHead()+printBody()+printTail()+'
    '; } show(); bindEvent(); }

    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

    转载请注明:文章转载自 www.mshxw.com
    本文地址:https://www.mshxw.com/it/88296.html
    我们一直用心在做
    关于我们 文章归档 网站地图 联系我们

    版权所有 (c)2021-2022 MSHXW.COM

    ICP备案号:晋ICP备2021003244-6号