基础概念: jQuery 是一个快速、简洁的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。在网页开发中,jQuery 常用于实现各种动态效果,包括分页功能。
优势:
类型:
应用场景:
示例代码(客户端分页):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery 分页示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.pagination {
margin-top: 20px;
}
.pagination a {
padding: 5px 10px;
margin-right: 5px;
border: 1px solid #ccc;
text-decoration: none;
}
.pagination a.active {
background-color: #007bff;
color: white;
border-color: #007bff;
}
</style>
</head>
<body>
<ul id="itemList">
<!-- 列表项将通过 jQuery 动态生成 -->
</ul>
<div class="pagination">
<!-- 分页链接将通过 jQuery 动态生成 -->
</div>
<script>
$(document).ready(function() {
var itemsPerPage = 10; // 每页显示的项目数
var currentPage = 1; // 当前页码
var data = []; // 假设这是从服务器获取的数据数组
// 初始化数据(模拟)
for (var i = 1; i <= 100; i++) {
data.push('Item ' + i);
}
function displayItems(page) {
var start = (page - 1) * itemsPerPage;
var end = start + itemsPerPage;
var pageData = data.slice(start, end);
$('#itemList').empty();
for (var i = 0; i < pageData.length; i++) {
$('#itemList').append('<li>' + pageData[i] + '</li>');
}
}
function setupPagination() {
var totalPages = Math.ceil(data.length / itemsPerPage);
$('.pagination').empty();
for (var i = 1; i <= totalPages; i++) {
$('.pagination').append('<a href="#" class="' + (i === currentPage ? 'active' : '') + '">' + i + '</a>');
}
$('.pagination a').click(function(e) {
e.preventDefault();
currentPage = parseInt($(this).text());
displayItems(currentPage);
setupPagination(); // 更新分页链接状态
});
}
displayItems(currentPage);
setupPagination();
});
</script>
</body>
</html>
常见问题及解决方法:
itemsPerPage
和 currentPage
的计算逻辑。displayItems
和 setupPagination
函数。通过以上步骤和代码示例,可以实现一个基本的 jQuery 分页功能,并解决常见的分页问题。