Html & Script

자바스크립트로 페이징하기

컨텐츠 정보

본문

글쓴이:거친마루  자바스크립트로 페이징하기 조회수:3478


 http://sample.e-wut.co.kr/paging.html
 http://sample.e-wut.co.kr/js/lib.paging.js



이번에 뭔가를 만들다가 페이징이 참 귀찮은 부분이다라고 생각이 들어서 이걸 자바스크립트로 한번 구현해봤습니다. 오라클을 쓸때와 mysql을 쓸때 쿼리가 살짝살짝 달라서 일반적인 뭔가를 만들기가 참 힘들었담 말이죠... 로직은 일반적으로 php에서 쓰는것과 다를게 없고 잘만 응용하면 서버 부하도 분산시킬 수 있는 괜찮은 장난감이 될꺼같아서.만들어봤습니다.

예제: http://sample.e-wut.co.kr/paging.html

예제를 보시면 돌아가는걸 간단히 확인하실 수 있습니다.

소스: http://sample.e-wut.co.kr/js/lib.paging.js

소스코드를 보시면 QueryString 클래스오브젝트와 Paging 클래스 오브젝트가 있습니다. QueryString 은 따로 나눠야 정석이지만.. 일단은 한가지로 합쳤습니다. 두번 로드하는건 웬지 귀찮아보여서^^
간단히 2시간정도 투자해서 만든거라 아직 부족한부분이 많습니다. 보시고 이쁘게 다듬어주시길.. 

코드:
QueryString = function(str) {
  var str = str ? str : document.location.href;
  this.argv = new Array();
  this.queryString = str.split('?')[1];
  if (!this.queryString) this.queryString = '';
  var _argv = this.queryString.split('&');
  for(var i=0; i<_argv.length; i++) {
      $=_argv[i].split('=');
      var _key = $[0];
      var _val = $[1];
      this.argv[_key] = $[1];
  }

  if (!this.argv) this.argv = new Array();

  this.setVar = function(key,val) {
      if (typeof key == 'object') {
        for (var item in key) this.argv[item] = key[item];
      } else {
        this.argv[key] = val;
      }
      return this.getVar();
  }

  this.getVar = function(key) {
      if (key) {
        if (!this.argv[key]) return '';
        else {
            return this.argv[key];
        }
      } else {
        var cnt = 0;
        for(var c in this.argv) cnt++;  // XXX: 키 이름을 가진 array 는 length 속성으로 항상 0 을 벹어낸다.
        if (cnt > 0) {
            var _item = new Array();
            for (var x in this.argv) if (this.argv[x]) _item[_item.length] = x + '=' + this.argv[x];
            else continue;
            return '?' + _item.join('&');
        } else return '?';
      }
  }
}

Paging = function(total) {
  this.config = {
      thisPageStyle: 'font-weight: bold;',
      itemPerPage: 10,  // 리스트 목록수
      pagePerView: 10      // 페이지당 네비게이션 항목수
  }

  this.totalItem = total;
  this.qs = new QueryString;

  this.calculate = function() {
      this.totalPage = Math.ceil(this.totalItem / this.config.itemPerPage);
      this.currentPage = this.qs.getVar('page');
      if (!this.currentPage) this.currentPage = 1;
      if (this.currentPage > this.totalPage) this.currentPage = this.totalPage;
      this.lastPageItems = this.totalPage % this.config.itemPerPage;

      this.prevPage = this.currentPage-1;
      this.nextPage = this.currentPage+1;
      this.seek = this.prevPage * this.config.itemPerPage;
      this.currentScale = parseInt(this.currentPage / this.config.pagePerView);
      if (this.currentPage % this.config.pagePerView < 1) this.currentScale--;
      this.totalScale = parseInt(this.totalPage / this.config.pagePerView);
      this.lastScalePages = this.totalPage % this.config.pagePerView;
      if (this.lastScalePages == 0) this.totalScale--;
      this.prevPage = this.currentScale * this.config.pagePerView;
      this.nextPage = this.prevPage + this.config.pagePerView + 1;
  }

  this.toString = function() {
      var ss, se;
      this.calculate();
      if (this.config.prevIcon) var prevBtn ='<img src="'+this.config.prevIcon+'" border="0" align="absmiddle">';
      else var prevBtn = '◀';
      if (this.currentPage > this.config.pagePerView) {
        prevBtn = prevBtn.link(this.qs.setVar('page',this.prevPage));
      }

      ss = this.prevPage + 1;
      if ((this.currentScale >= this.totalScale) && (this.lastScalePages != 0)) se = ss + this.lastScalePages;
      else if (this.currentScale <= -1) se = ss;
      else se = ss + this.config.pagePerView;

      var navBtn = '';
      for(var i = ss; i<se; i++) {
        if (i == this.currentPage) {
            _btn = '<span style="'+this.config.thisPageStyle+'">['+i+']</span>';
        } else {
            _btn = '<a href="'+this.qs.setVar('page',i)+'" style="'+this.config.otherPageStyle+'">['+i+']</a>'
        }
        navBtn+=_btn;
      }

      if (this.config.prevIcon) var nextBtn ='<img src="'+this.config.nextIcon+'" border="0" align="absmiddle">';
      else var nextBtn = '▶';
      if (this.totalPage > this.nextPage) {
        nextBtn = nextBtn.link(this.qs.setVar('page',this.nextPage));
      }
      return prevBtn+navBtn+nextBtn;
  }
}

ps. 피드백은 http://maniacamp.com/bbs/viewtopic.php?t=29 로 : )

 
 

관련자료

댓글 0
등록된 댓글이 없습니다.
Today's proverb
유쾌한 사람은 자기 일에만 몰두하는 사람이 아니다. 때론 자신의 일을 전부 제쳐놓고 타인의 문제에 전력을 쏟는 열정이 있는 사람이다. 타인에게 자신의 힘을 나누어주고 마음을 열어주는 것은 자신의 삶을 행복하게 만드는 방법이다.