採用 $.fn.extend 擴展 jQuery 原型,以插件形式調用:$('#pager').JPager(config, pageIndex, pageSize)。核心功能模組:
cfg.callback(pageIndex, pageSize) 通知業務層加載數據$.fn.extend({
JPager: function(cfg, pageIndex, pageSize) {
var $container = this.empty();
var token = '#' + this.attr('id');
// 1. 計算總頁數
var totalPages = Math.ceil(cfg.recordCount / pageSize);
if (pageIndex < 1) pageIndex = 1;
if (pageIndex > totalPages) pageIndex = totalPages;
// 2. 生成導航按鈕
var html = '';
html += '<a id="_first" class="number">首頁</a>';
html += '<a id="_pre" class="number">上頁</a>';
// ... 頁碼區域 ...
html += '<a id="_next" class="number">下頁</a>';
html += '<a id="_last" class="number">末頁</a>';
html += '<input id="_pos" type="text" /><button id="_go">GO</button>';
html += '<span id="_left"></span><span id="_right"></span>'; // 自定義模板插槽
$container.html(html);
// 3. 綁定事件
$('#_first', $container).click(function() { $(token).JPager(cfg, 1, pageSize); });
$('#_pre', $container).click(function() { $(token).JPager(cfg, pageIndex-1, pageSize); });
$('#_next', $container).click(function() { $(token).JPager(cfg, pageIndex+1, pageSize); });
$('#_last', $container).click(function() { $(token).JPager(cfg, totalPages, pageSize); });
$('#_go', $container).click(function() {
var idx = parseInt($('#_pos').val());
$(token).JPager(cfg, idx, pageSize);
});
// 4. 頁碼區域渲染邏輯(省略:當前頁居中、省略號處理)
// ...
// 5. 狀態類切換
if (pageIndex === 1) $('#_first,#_pre', $container).addClass('unable');
if (pageIndex === totalPages) $('#_last,#_next', $container).addClass('unable');
// 6. 執行用戶回調
if (cfg.callback) cfg.callback(pageIndex, pageSize);
}
});
// HTML
<div id="pager"></div>
// JS
$('#pager').JPager({
recordCount: 156, // 總記錄數(必填)
pageSize: 10, // 每頁大小
callback: function(page, size) {
loadData(page, size); // 業務層請求數據
},
customer: {
template: '共 %total% 頁,當前第 %current% 頁,共 %recordCount% 條',
position: 'right'
}
}, 1, 10); // 初始第 1 頁
role="navigation"、aria-label、鍵盤導航支持。新專案建議使用成熟分頁組件:
el-pagination (Vue)Pagination (React/Vue)<nav aria-label="Pagination"> + Fetch API