DIV CSS 佈局教程網

手寫一個可複用的 JavaScript 分頁組件
編輯:JavaScript綜合知識     

分頁幾乎每個列表頁都要用。与其每次到處拷貝,不如封裝成一個組件:HTML 裡只需放一個容器,其餘全部交給 JS 生成。這個示例就是這樣的思路。

HTML:只留一個容器

<ul class="pagination" id="pageDIV"></ul>

class="pagination" 掛樣式,id="pageDIV" 供 JS 定位並填充分頁內容。

CSS:借用 Bootstrap 風格的視覺

.pagination{
  display: inline-block;
  padding-left: 0;
  margin: 20px 0;
  border-radius: 4px;
}
.pagination > li { display: inline; }
.pagination > li > a{
  position: relative;
  float: left;
  padding: 6px 12px;
  margin-left: -1px;
  line-height: 1.42857143;
  color: #337ab7;
  text-decoration: none;
  background-color: #fff;
  border: 1px solid #ddd;
  cursor: pointer;
}
.pagination > li:first-child > a{
  margin-left: 0;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
}
.pagination > li > a.navcur{      /* 當前頁高亮 */
  background: #cccccc;
  color: #ffffff;
}

關鍵是 margin-left: -1px 這個技巧:讓相鄰方塊的邊框重疊成一條線,看起來才像連貫的整體。當前頁則靠 navcur 類名標識。

JS:構造函數 + 原型方法

組件用經典的「構造函數 + prototype」模式組織(需先引入 jQuery):

/**
 * @pageContentID 渲染分頁的 DIV 元素 id
 * @curPage      當前頁
 * @totalCount   總記錄數
 * @pageRows     每頁顯示數量
 * @callback     翻頁後的數據加載回調
 */
function PageList(pageContentID, option){
  this.pageContentID = document.getElementById(pageContentID);
  this.curPage    = option.curPage;
  this.totalCount = option.totalCount;
  this.pageRows   = option.pageRows;
  this.callback   = option.callback;
  this.pageSize   = Math.ceil(this.totalCount / this.pageRows);   // 總頁數
}

PageList.prototype = {
  init: function(){
    this.renderbtn();
  },

  // 首頁
  firstpage: function () {
    var _self = this;
    _self._firstpage   = document.createElement("li");
    _self._firstpageA  = document.createElement("a");
    _self._firstpageA.innerHTML = "首頁";
    _self._firstpage.appendChild(_self._firstpageA);
    this.pageContentID.appendChild(_self._firstpage);
    _self._firstpage.onclick = function(){
      _self.gotopage(1);
    };
  },

  // 尾頁
  lastpage: function () {
    var _self = this;
    _self._lastpage   = document.createElement("li");
    _self._lastpageA  = document.createElement("a");
    _self._lastpageA.innerHTML = "尾頁";
    _self._lastpage.appendChild(_self._lastpageA);
    this.pageContentID.appendChild(_self._lastpage);
    _self._lastpage.onclick = function(){
      _self.gotopage(_self.pageSize);
    };
  },

  // 上一頁
  prewpage: function () {
    var _self = this;
    _self._prew   = document.createElement("li");
    _self._prewA  = document.createElement("a");
    _self._prewA.innerHTML = "<<";
    _self._prew.appendChild(_self._prewA);
    this.pageContentID.appendChild(_self._prew);
    _self._prew.onclick = function(){
      if (_self.curPage > 1) { _self.curPage--; }
      _self.callback.call(this, _self.curPage);
      _self.init();
    };
  },

  // 下一頁
  nextpage: function () {
    var _self = this;
    _self._next   = document.createElement("li");
    _self._nextA  = document.createElement("a");
    _self._nextA.innerHTML = ">>";
    _self._next.appendChild(_self._nextA);
    this.pageContentID.appendChild(_self._next);
    _self._next.onclick = function(){
      if (_self.curPage < _self.pageSize) { _self.curPage++; }
      _self.callback.call(this, _self.curPage);
      _self.init();
    };
  },

  // 頁碼列表:以 10 頁為一組
  pagenum: function () {
    var _self = this;
    var start, end;

    if (this.pageSize <= 10) {
      start = 1; end = this.pageSize;
    } else if (_self.curPage <= 10) {
      start = 1; end = 10;
    } else {
      start = Math.floor((_self.curPage - 1) / 10) * 10 + 1;
      end   = Math.min(start + 9, this.pageSize);
    }

    for (var i = start; i <= end; i++) {
      (function (num) {
        var li = document.createElement("li");
        var a  = document.createElement("a");
        a.innerHTML = num;
        li.appendChild(a);
        _self.pageContentID.appendChild(li);
        li.onclick = function(){
          _self.gotopage(num);
        };
      }(i));
    }

    // 標記當前頁
    $(".pagination li").each(function(){
      if ($(this)[0].innerText == _self.curPage) {
        $(".pagination li").children("a").removeClass("navcur");
        $(this).children("a").addClass("navcur");
      }
    });
  },

  gotopage: function (curpage) {
    this.curPage = curpage;
    this.callback.call(this, this.curPage);
    this.init();
  },

  renderbtn: function () {
    $(".pagination").html("");
    this.firstpage();
    this.prewpage();
    this.pagenum();
    this.nextpage();
    this.lastpage();
  }
};

調用方式

$(function(){
  var pager = new PageList("pageDIV", {
    curPage: 1,
    totalCount: 26,
    pageRows: 1,
    callback: callbackFuc
  });
  pager.init();
});

function callbackFuc(curpage){
  // 在這裡根據 curpage 請求並渲染數據
}

原示例的幾處問題與改進

原始版本功能可用,但有些細節值得修正,這裡一併指出:

· 閉包捕獲陷阱。原代碼在 for 迴圈中直接給 li.onclick 賦值,所有閉包共享同一個循環變量 i,點擊任何頁碼都可能跳到最後一頁。上面已改用 IIFE 傳參,或改用 let 解決。

· 頁碼組的邊界計算過於繁瑣。原實現用多層 if/else 配合 Math.ceil(curPage/10)*10 反覆推算,分支多且難以驗證。改為先算出 start 與 end 再單一迴圈生成,邏輯清楚得多。

· innerText 兼容性。老版 Firefox 不支援該屬性,應改用 $.trim($(this).text()) 更穩妥。

· 每次翻頁全量重建 DOM。renderbtn() 會清空並重建所有按鈕,頁面複雜時開銷不小。可以只更新 navcur 類名與首尾頁的禁用狀態。

· 缺少邊界禁用。首頁時「上一頁」仍舊可點,實用上應加上禁用樣式。

· 大量重複的 DOM 創建代碼。六個方法裡幾乎相同,抽一個 createBtn(text, handler) 輔助函數即可大幅精簡。

整體來說,這個組件的骨架——配置對象傳參、原型方法組織、callback 回調取數據、以 10 頁為一組的窗口策略——是相當實用的參考範式,修正上述細節後即可放心複用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved