前端分頁本質:全量數據一次性獲取 → 客戶端切片 → 按頁顯示對應切片 → 隱藏其餘行。適合數據量較小(< 500 條)的靜態/緩存場景。
(function($) {
$.fn.tablepage = function(pageContainer, pageSize, freshId) {
var $table = $(this), currentPage = 1, totalPages;
var $pager = $(pageContainer);
function render() {
var rows = $table.children().children('tr'); // 假設 tbody > tr
var total = rows.length;
totalPages = Math.ceil(total / pageSize);
// 1. 生成分頁 HTML
var html = "<div class='ref'><a href='javascript:void(0)' id='fresh_" + freshId + "' class='sx'>刷新</a></div>";
html += "<div class='msdn'><a>首頁</a><a>上一頁</a><a>下一頁</a><a>尾頁</a></div>";
html += "<div class='txt'>共" + totalPages + "頁,當前第<strong>" + currentPage + "</strong>頁</div>";
$pager.html(html);
// 2. 顯示/隱藏行
rows.each(function(i) {
var page = Math.floor(i / pageSize) + 1;
$(this).toggle(page === currentPage);
});
// 表頭始終顯示
rows.first().show();
// 3. 禁用不可用按鈕
$pager.find('.msdn a').each(function(i) {
var txt = $(this).text();
if ((txt === '首頁' || txt === '上一頁') && currentPage === 1) $(this).addClass('disabled');
if ((txt === '尾頁' || txt === '下一頁') && currentPage === totalPages) $(this).addClass('disabled');
});
// 4. 綁定點擊事件
$pager.find('.msdn a').off('click').on('click', function() {
var txt = $(this).text();
if (txt === '首頁') currentPage = 1;
else if (txt === '尾頁') currentPage = totalPages;
else if (txt === '上一頁' && currentPage > 1) currentPage--;
else if (txt === '下一頁' && currentPage < totalPages) currentPage++;
else return;
render();
});
}
render();
};
})(jQuery);
// 使用
$('#studentTable').tablepage('#pager', 10, 'student');
<script>
$(function() {
var $items = $('ul li'), pageSize = 5;
var total = $items.length, pages = Math.ceil(total / pageSize);
var current = 1;
if (total <= pageSize) {
$('#btnPrev, #btnNext').addClass('disabled').prop('disabled', true);
return;
}
$items.hide().slice(0, pageSize).show();
$('#btnPrev').click(function() {
if (current <= 1) return;
current--;
showPage(current);
});
$('#btnNext').click(function() {
if (current >= pages) return;
current++;
showPage(current);
});
function showPage(page) {
$items.hide();
var start = (page - 1) * pageSize;
$items.slice(start, start + pageSize).show();
$('#btnPrev').toggleClass('disabled', page === 1).prop('disabled', page === 1);
$('#btnNext').toggleClass('disabled', page === pages).prop('disabled', page === pages);
}
});
</script>
| 場景 | 推薦方案 |
|---|---|
| 數據量 < 500、靜態內容、SEO 不敏感 | 前端分頁(本文方案) |
| 數據量大、需 SEO、權限控制 | 後端分頁(API 返回 page/data/total) |
| 實時數據、頻繁增刪改 | 後端分頁 + 前端樂觀更新 |
Pagination(total, pageSize, onChange) 復用。