DIV CSS 佈局教程網

用 jQuery 打造可自訂的分頁控件 JPager 完整示例
編輯:JQuery特效代碼     

分頁是列表頁的標配。下面這個 JPager 以 jQuery 外掛形式實作,透過 AJAX 向後端取資料、動態產生頁碼、支援跳頁與自訂樣板,並在首尾頁自動停用按鈕。

一、JavaScript(JPager.js)

$.fn.extend({
  JPager: function (cfg, pageIndex, pageSize) {
    if (cfg && pageIndex > 0 && pageSize > 0) {
      var token = "#" + this.attr("id");
      this.empty();

      var pageFirst = function () { $(token).JPager(cfg, 1, pageSize); };
      var pagePre   = function () { $(token).JPager(cfg, pageIndex - 1, pageSize); };
      var pageLast  = function () {
        $(token).JPager(cfg, parseInt($("#_tot").val()), pageSize);
      };
      var pageNext  = function () { $(token).JPager(cfg, pageIndex + 1, pageSize); };
      var pageNumber = function () {
        $(token).JPager(cfg, parseInt($(this).text()), pageSize);
      };

      // 跳頁:需處理超出上下限的輸入
      var pageGo = function () {
        var index = parseInt($("#_pos").val());
        var total = parseInt($("#_tot").val());
        if (index) {
          if (index > total)      $(token).JPager(cfg, total, pageSize);
          else if (index < 1)     $(token).JPager(cfg, 1, pageSize);
          else                    $(token).JPager(cfg, index, pageSize);
        }
      };

      var checkGoNumber = function () {
        this.value = Number(this.value) ? Number(this.value) : "";
      };

      // 自訂樣板:支援 %total% %current% %recordCount% %pageSize% 佔位符
      var initCustomer = function (recordCount) {
        if (cfg.customer && cfg.customer.template) {
          var t = cfg.customer.template;
          t = t.replace(/\%total\%/gi, Math.ceil(recordCount / pageSize))
               .replace(/\%current\%/gi, pageIndex)
               .replace(/\%recordCount\%/gi, recordCount)
               .replace(/\%pageSize\%/gi, pageSize);
          if (cfg.customer.position == "right") $("#_right").after(t);
          else $("#_left").before(t);
        }
      };

      // 首尾頁停用
      var changeState = function (total) {
        if (pageIndex == 1) {
          $("#_first").attr("class", "unable");
          $("#_pre").attr("class", "unable");
        } else {
          $("#_first").bind("click", pageFirst).attr("class", "number");
          $("#_pre").bind("click", pagePre).attr("class", "number");
        }
        if (pageIndex == total) {
          $("#_last").attr("class", "unable");
          $("#_next").attr("class", "unable");
        } else {
          $("#_last").bind("click", pageLast).attr("class", "number");
          $("#_next").bind("click", pageNext).attr("class", "number");
        }
      };

      // 頁碼視窗:只顯示 current 附近的 count 個頁碼
      var initNumber = function (total, count, current) {
        if (total > 0 && count > 0) {
          if (current < 1) current = 1;
          if (current > total) current = total;

          var endIndex = total, startIndex = 1;
          var temp = current + Math.floor(count / 2);
          if (temp < total) {
            if (temp < count) endIndex = count;
            else { startIndex = temp - count + 1; endIndex = temp; }
          } else if (total > count) {
            startIndex = total - count + 1;
          }

          $("#_number").empty();
          for (var i = startIndex; i <= endIndex; i++) {
            var html = $("<span></span>").text(i).bind("click", pageNumber);
            $("#_number").append(
              html.attr("class", i == current ? "selected" : "number")
            );
          }
        }
      };

      var initPager = function (data) {
        if ($.isArray(data.SearchResult) && data.RecordCount > 0) {
          $(token).append(
            "<span id='_left'><span id='_first' class='spcial'>首頁</span> " +
            "<span id='_pre' class='spcial'>上一頁</span></span> " +
            "<span id='_number'></span>" +
            "<span id='_go'><input id='_pos' type='text'/>" +
            "<input id='_to' type='button' value='GO'/></span> " +
            "<span id='_right'><span id='_next' class='spcial'>下一頁</span> " +
            "<span id='_last' class='spcial'>末頁</span></span>" +
            "<input id='_tot' type='hidden'/>"
          );
          var total = Math.ceil(data.RecordCount / pageSize);
          $("#_tot").val(total);
          $("#_pos").bind("blur", checkGoNumber);
          $("#_to").bind("click", pageGo);

          changeState(total);
          if (cfg.showNumber && cfg.count > 0) initNumber(total, cfg.count, pageIndex);
          initCustomer(data.RecordCount);
        }
      };

      // 發請求:把 pageIndex / pageSize 併入既有條件
      if (cfg.action && cfg.action.url && cfg.action.data) {
        var d = cfg.action.data.substr(0, cfg.action.data.lastIndexOf("}"))
              + ',"pageIndex":' + pageIndex + ',"pageSize":' + pageSize + "}";
        $.ajax({
          type: "post",
          url: cfg.action.url,
          dataType: "json",
          contentType: "text/json",
          data: d,
          success: function (data) {
            initPager(data.d);
            if (cfg.action.callback && $.isFunction(cfg.action.callback)) {
              cfg.action.callback(data.d);
            }
          }
        });
      }
    }
  }
});

二、CSS(JPager.css)

#_pos { width:40px; }
.unable { color:#BCC0BB; }
.number {
  margin:2px; color:#0000FF; text-decoration:underline;
}
.selected {
  margin:2px; color:#FF0000; font-weight:bold;
}

三、HTML 呼叫端

<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>分頁控件示例</title>
<link href="CSS/JPager.css" rel="stylesheet" type="text/css" />
<script src="JS/jquery.min.js" type="text/javascript"></script>
<script src="JExtension/JPager.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
    $("#pager").JPager({
        customer: { template: "%current% / %total% 頁,共 %recordCount% 筆" },
        count: 10,
        action: { url: "Service/JService.svc/GetPersons", data: '{"name":"zhoulq"}' },
        showNumber: true
    }, 1, 5);
});
</script>
</head>
<body>
<table></table>
<div id="pager"></div>
</body>
</html>

四、後端服務(WCF)

using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace JPlugin
{
    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class JService
    {
        [OperationContract]
        [WebInvoke]
        public PageObject<Person> GetPersons(string name, int pageIndex, int pageSize)
        {
            return new PageObject<Person>(){
                RecordCount = 23,
                SearchResult = new List<Person>(){
                    new Person(){ Name = "zhoulq", Age = 28 },
                    new Person(){ Name = "zhouxy", Age = 24 }
                }
            };
        }
    }

    public class PageObject<T>
    {
        public int RecordCount { get; set; }
        public List<T> SearchResult { get; set; }
    }
}

設計上的幾個觀察

頁碼視窗演算法是這個元件最花心思的部分:以目前頁為中心、往前後各取一半,並在接近頭尾時把視窗貼齊邊界,避免頁碼區寬度跳動。這是實用分頁元件的標準做法,值得細讀。

資料格式由後端決定。程式碼依賴 RecordCount 與 SearchResult 兩個欄位,且僅支援 data.d 這種 ASP.NET Web 服務的包裝格式。若要接到一般的 REST 或 Web API,需要調整 success 回呼的取值路徑。

身分驗證不可省。示例的 WCF 服務沒有任何驗證就回傳資料,正式環境務必加上身分與權限檢查,並對 name 這類查詢參數做參數化處理;字串拼接 SQL 是這個年代不該再出現的寫法。

可維護性建議:元件大量使用 #_first、#_pos 這類全域 id,同一頁只能存在一個分頁元件;若有多個列表需要分頁,id 會互相衝突。改用元件內的相對選擇器(例如 this.find("span[data-act='first']"))並以 data- 屬性標示角色,就能支援多實例。另外 bind() 在 jQuery 3 已移除,請改用 on()。

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