jquery 翻页
jQuery 翻页实现方法
基础翻页结构
使用简单的HTML和jQuery实现翻页功能,需包含页码按钮和内容容器:
<div class="pagination">
<button class="prev">上一页</button>
<span class="page-numbers"></span>
<button class="next">下一页</button>
</div>
<div class="content-container"></div>
动态生成页码
通过jQuery动态计算并渲染页码按钮,需定义总页数和当前页:
let currentPage = 1;
const totalPages = 10;
function renderPagination() {
$('.page-numbers').empty();
for (let i = 1; i <= totalPages; i++) {
$('.page-numbers').append(`<button class="page-btn ${i === currentPage ? 'active' : ''}">${i}</button>`);
}
}
翻页事件绑定
为页码按钮和导航按钮添加点击事件处理:
$(document).on('click', '.page-btn', function() {
currentPage = parseInt($(this).text());
loadPageContent();
});
$('.prev').click(function() {
if (currentPage > 1) {
currentPage--;
loadPageContent();
}
});
$('.next').click(function() {
if (currentPage < totalPages) {
currentPage++;
loadPageContent();
}
});
AJAX加载内容
结合AJAX实现动态内容加载(需后端接口支持):
function loadPageContent() {
$.ajax({
url: '/api/data',
data: { page: currentPage },
success: function(response) {
$('.content-container').html(response.data);
renderPagination();
}
});
}
样式优化建议
为当前页码添加高亮样式,增强用户体验:
.page-numbers button.active {
background-color: #007bff;
color: white;
}
.pagination button {
margin: 0 5px;
padding: 5px 10px;
cursor: pointer;
}
完整示例代码
整合所有功能的完整实现示例:

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.pagination { margin: 20px 0; }
.page-numbers button { margin: 0 5px; }
.active { font-weight: bold; color: red; }
</style>
</head>
<body>
<div class="pagination">
<button class="prev">上一页</button>
<span class="page-numbers"></span>
<button class="next">下一页</button>
</div>
<div class="content-container"></div>
<script>
$(function() {
let currentPage = 1;
const totalPages = 5;
function renderPagination() {
$('.page-numbers').empty();
for (let i = 1; i <= totalPages; i++) {
$('.page-numbers').append(
`<button class="page-btn ${i === currentPage ? 'active' : ''}">${i}</button>`
);
}
}
function loadPageContent() {
$('.content-container').html(`当前显示第 ${currentPage} 页内容`);
renderPagination();
}
$(document).on('click', '.page-btn', function() {
currentPage = parseInt($(this).text());
loadPageContent();
});
$('.prev').click(function() {
if (currentPage > 1) {
currentPage--;
loadPageContent();
}
});
$('.next').click(function() {
if (currentPage < totalPages) {
currentPage++;
loadPageContent();
}
});
// 初始化
loadPageContent();
});
</script>
</body>
</html>
注意事项
- 总页数通常由后端接口返回,示例中使用固定值简化实现
- 实际项目中建议添加加载状态提示和错误处理
- 移动端适配可考虑使用响应式布局或滑动翻页组件
- 大数据量时建议实现分页缓存机制






