分頁是列表頁的標配。與其每頁重寫一次,不如封裝成 jQuery 外掛,透過設定檔驅動版面與行為。以下示範一個支援首頁/上一頁/頁碼/下一頁/末頁、跳頁輸入框與自訂樣板的 JPager 控件。
$(function () {
$("#pager").JPager({
count: 10, // 顯示幾個頁碼鈕
showNumber: true, // 是否顯示頁碼
customer: { template: "%cuRRent%" },
action: {
url: "Service/JService.svc/GetPersons",
data: '{"name":"zhoulq"}'
}
}, 1, 5); // 初始頁碼 1,每頁 5 筆
});
$.fn.extend({
JPager: function (cfg, pageIndex, pageSize) {
if (!cfg || pageIndex <= 0 || pageSize <= 0) return;
var token = "#" + this.attr("id");
this.empty();
// ---- 各項導航行為:都統一回到 JPager 重新渲染 ----
var pageFirst = function () { $(token).JPager(cfg, 1, pageSize); };
var pagePre = function () { $(token).JPager(cfg, pageIndex - 1, pageSize); };
var pageNext = function () { $(token).JPager(cfg, pageIndex + 1, pageSize); };
var pageLast = function () {
$(token).JPager(cfg, parseInt($("#_tot").val()), 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) return;
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) : "";
};
// ---- 依目前頁碼切換首/上/下/末的 disabled 狀態 ----
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");
}
};
// ---- 頁碼視窗:只顯示目前頁附近的 count 個數字 ----
var initNumber = function (total, count, current) {
if (total <= 0 || count <= 0) return;
if (current < 1) current = 1;
if (current > total) current = total;
var startIndex = 1, endIndex = total;
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(
i == current ? html.attr("class", "selected")
: html.attr("class", "number")
);
}
};
// ---- 自訂樣板:可插入總頁數、目前頁、總筆數等資訊 ----
var initCustomer = function (recordCount) {
if (!cfg.customer || !cfg.customer.template) return;
var t = cfg.customer.template
.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 initPager = function (data) {
if (!($.isArray(data.SearchResult) && data.RecordCount > 0)) return;
$(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 併進既有 data ----
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);
}
}
});
}
}
});
#_pos { width: 40px; }
.unable { color: #BCC0BB; } /* 不可點擊的灰階狀態 */
.number { margin: 2px; color: #0000FF; text-decoration: underline; }
.selected { margin: 2px; color: #FF0000; font-weight: bold; }
[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 = "zhpulq", Age = 28 },
new Person { Name = "zhouxy", Age = 24 }
}
};
}
}
public class PageObject<T>
{
public int RecordCount { get; set; }
public List<T> SearchResult { get; set; }
}
這份實作的思路清楚,但有幾處值得調整:一是大量使用 #_first、#_pos 這類全域 id,同一頁放兩個分頁器就會互相打架,改用具名 scope(例如 $(token).find('.js-first'))更穩;二是每次翻頁都把整個控件 empty() 重畫,可以只更新頁碼區與 disabled 狀態;三是 attr("class", ...) 應改用 addClass/removeClass,避免把其他樣式類一起洗掉;四是 bind() 在新版 jQuery 已改名為 on()。這些屬於維護面的建議,不影響主流程的正確性。