本範例示範如何使用純 jQuery 實現:
var countPage = 0; // 總頁數
var nowPage = 1; // 目前頁碼
var pageSize = 5; // 每頁筆數
var countSize = 0; // 總資料筆數
var startIndex = 0; // 起始索引
var endIndex = 0; // 結束索引
$(document).ready(function() {
// 1. 新增資料事件
$("#submit").click(function() {
var name = $("#name").val();
var sex = $("input[name='sex']:checked").val();
var age = $("#age").val();
pageSize = $("#selectSize option:selected").val();
// 動態建立表格列
var $tr = $(" ");
$tr.append($(" ").html(""));
$tr.append($(" ").text(name));
$tr.append($(" ").text(sex));
$tr.append($(" ").text(age));
$tr.append($(" ").html(""));
$("#show").append($tr);
pagination(); // 重新計算分頁
});
// 2. 每頁筆數變更
$("#selectSize").change(function() {
pageSize = $(this).val();
pagination();
});
// 3. 分頁按鈕綁定
$("#first, #back, #next, #last").click(pagination);
});
// 分頁核心函式
function pagination() {
// 取得所有資料列(含標題列需注意)
countSize = $("#show tr").size();
countPage = Math.ceil(countSize / pageSize);
// 判斷觸發來源(按鈕點擊 vs 程式呼叫)
if (this.nodeType === 1) { // 為 DOM 元素時
var btnId = $(this).attr("id");
switch (btnId) {
case "first": nowPage = 1; break;
case "back": if (nowPage > 1) nowPage--; break;
case "next": if (nowPage < countPage) nowPage++; break;
case "last": nowPage = countPage; break;
}
}
// 計算顯示範圍
startIndex = (nowPage - 1) * pageSize;
endIndex = nowPage * pageSize - 1;
if (endIndex >= countSize) endIndex = countSize - 1;
// 顯示/隱藏對應列
$("#show tr").hide(); // 先全部隱藏
$("#show tr").slice(startIndex, endIndex + 1).show();
// 更新資訊列
$("#sizeInfo").html("目前第 " + (startIndex+1) + " 至 " + (endIndex+1) + " 筆,共 " + countSize + " 筆");
$("#pageInfo").html("第 " + nowPage + " 頁,共 " + countPage + " 頁");
}
<div id="content" align="center">
<form>
<!-- 左側輸入區 -->
<div id="insertDiv">
<table id="insertData" border="1">
<tr><td>姓名<input type="text" id="name" value="donghogyu"></td></tr>
<tr><td>性別
<input type="radio" name="sex" value="男" checked>男
<input type="radio" name="sex" value="女">女
</td></tr>
<tr><td>年齡<input type="text" id="age" value="21"></td></tr>
<tr><td align="center"><input type="button" id="submit" value="新增資料"></td></tr>
</table>
</div>
<!-- 右側表格區 -->
<div id="tableDiv">
<div id="top">
<table id="topTable" border="1">
<thead>
<tr>
<th><input type="checkbox">全選</th>
<th>姓名</th><th>性別</th><th>年齡</th><th>操作</th>
</tr>
</thead>
<tbody id="show"></tbody>
</table>
</div>
<!-- 分頁工具列 -->
<div id="bottom">
<table id="bottomTable" border="1">
<tr align="center">
<td><input type="button" value="首頁" id="first"></td>
<td><input type="button" value="上一頁" id="back"></td>
<td><input type="button" value="下一頁" id="next"></td>
<td><input type="button" value="末頁" id="last"></td>
<td>
<select id="selectSize">
<option value="3">3</option>
<option value="5" selected>5</option>
<option value="10">10</option>
</select>
</td>
</tr>
</table>
<div id="sizeInfo"></div>
<div id="pageInfo"></div>
</div>
</div>
</form>
</div>
tr 後重新分頁此範例展示了前端分頁的基本原理:資料全量載入 → 計算分頁參數 → 控制 DOM 顯示/隱藏。適合資料量較小(百筆內)的後台管理介面。實務上若資料量大,務必改用伺服器端分頁。