當資料量不大、又不想每次都跟後端溝通時,可以考慮在前端用 jQuery 實作表格的新增與分頁。以下是一個完整的範例。
var countPage;
var nowPag = 1;
var pageSize;
var countSize;
var starIndex;
var endIndex;
var name;
var sex;
var age;
var num = 1;
$(document).ready(function() {
$("#submit").click(function() {
name = $("#name").val();
sex = $("input[name='sex']:checked").val();
age = $("#age").val();
pageSize = $("#selectSize option:selected").val();
$tr = $("<tr class='data' ></tr>");
$td1 = $("<td></td>");
$td2 = $("<td></td>");
$td3 = $("<td></td>");
$td4 = $("<td></td>");
$td5 = $("<td></td>");
$tr.append($td1.append("<input type='checkbox'>"));
$tr.append($td2.append(name));
$tr.append($td3.append(sex));
$tr.append($td4.append(age));
$tr.append($td5.append("<input type='button' value='刪除'>"));
$("#show").append($tr);
pageNation();
});
$("#selectSize").change(function() {
pageSize = $("#selectSize option:selected").val();
pageNation();
});
$("#first").click(pageNation);
$("#back").click(pageNation);
$("#next").click(pageNation);
$("#last").click(pageNation);
});
var pageNation = function() {
countSize = $("#show tr").size();
countPage = Math.ceil(countSize / pageSize);
if (this.nodeType == 1) {
var idValue = $(this).attr("id");
if ("first" == idValue) {
nowPag = 1;
} else if ("back" == idValue) {
if (nowPag > 1) { nowPag--; }
} else if ("next" == idValue) {
if (nowPag < countPage) { nowPag++; }
} else if ("last" == idValue) {
nowPag = countPage;
}
}
starIndex = (nowPag - 1) * pageSize + 1;
endIndex = nowPag * pageSize;
if (endIndex > countSize) { endIndex = countSize; }
if (countSize < pageSize) { endIndex = countSize; }
if (starIndex == endIndex) {
$("#show tr:eq(" + (starIndex - 1) + ")").show();
$("#show tr:lt(" + (starIndex - 1) + ")").hide();
} else {
$("#show tr:gt(" + (starIndex - 1) + ")").show();
$("#show tr:lt(" + (endIndex - 1) + ")").show();
$("#show tr:lt(" + (starIndex - 1) + ")").hide();
$("#show tr:gt(" + (endIndex - 1) + ")").hide();
}
$("#sizeInfo").html("當前從" + starIndex + "條到第" + endIndex + "條記錄,共" + countSize + "條記錄.");
$("#pageInfo").html("當前是第" + nowPag + "頁,共" + countPage + "頁.");
};
這個範例的關鍵概念是:先算出總筆數與總頁數,再依據當前頁碼計算出要顯示的起訖索引,最後用 jQuery 的 :lt、:gt、:eq 選擇器,精準地顯示該頁範圍內的列、隱藏其餘的列。新增資料時只要 append 一列新的 tr 再重新呼叫分頁函式即可。这种做法的好處是無需後端參與、反應即時,很適合資料量固定的小型應用。