jquery 分页
jQuery 分页实现方法
jQuery 分页可以通过多种方式实现,包括使用插件或手动编写代码。以下是几种常见的实现方法。
使用 jQuery Pagination 插件
引入 jQuery 和 pagination 插件库:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://pagination.js.org/dist/2.1.5/pagination.min.js"></script>
<link rel="stylesheet" href="https://pagination.js.org/dist/2.1.5/pagination.css">
初始化分页:
$(document).ready(function() {
$('#pagination-container').pagination({
dataSource: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
pageSize: 3,
callback: function(data, pagination) {
var html = template(data);
$('#data-container').html(html);
}
});
});
function template(data) {
var html = '';
$.each(data, function(index, item) {
html += '<div>' + item + '</div>';
});
return html;
}
手动实现分页逻辑
定义分页函数:

function paginate(items, pageNumber, pageSize) {
const startIndex = (pageNumber - 1) * pageSize;
return items.slice(startIndex, startIndex + pageSize);
}
绑定分页事件:
$(document).ready(function() {
const allItems = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const pageSize = 3;
let currentPage = 1;
function renderPage() {
const pageItems = paginate(allItems, currentPage, pageSize);
$('#data-container').empty();
$.each(pageItems, function(i, item) {
$('#data-container').append('<div>' + item + '</div>');
});
}
$('#prev-btn').click(function() {
if (currentPage > 1) {
currentPage--;
renderPage();
}
});
$('#next-btn').click(function() {
if (currentPage < Math.ceil(allItems.length / pageSize)) {
currentPage++;
renderPage();
}
});
renderPage();
});
使用 DataTables 插件实现分页
引入 DataTables 库:

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.css">
<script type="text/javascript" src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.js"></script>
初始化表格分页:
$(document).ready(function() {
$('#example').DataTable({
"pagingType": "full_numbers",
"pageLength": 5
});
});
分页注意事项
确保分页逻辑与数据加载方式匹配,避免一次性加载大量数据导致性能问题。
分页控件应提供明确的导航选项,包括页码跳转、上一页和下一页按钮。
对于动态加载的数据,考虑使用 AJAX 分页,每次只请求当前页的数据。






