You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为现有jQuery分页代码添加页面刷新记忆当前页功能?

实现分页刷新后记住当前页码

要让分页在页面刷新后记住当前页码,直接用浏览器的localStorage存储当前选中的页码即可,以下是修改后的完整代码及关键说明:

关键修改点

  • 点击页码时,将当前页的rel值存入localStorage
  • 页面初始化阶段,优先读取localStorage中保存的页码,无值则默认显示第1页

修改后的完整代码

$('.table-wrap').after('<div class="pagination-wrap"></div>');
$('.pagination-wrap').append('<div class="pagination"></div>');
$('.pagination').append('<ul class="pagination__list"></ul>');
var rowsShown = 10;
var rowsTotal = $('.table tbody tr').length;
var numPages = rowsTotal/rowsShown;
for(i = 0; i < numPages; i++) {
    var pageNum = i + 1;
    $('.pagination__list').append('<li class="pagination__item" rel="'+i+'"><a class="pagination__link" href="#">'+pageNum+'</a></li>');
}

// 初始化时读取本地存储的页码,默认0(对应第1页)
var savedPage = localStorage.getItem('currentPage') || 0;
$('.table tbody tr').hide();
// 根据保存的页码显示对应行
var startItem = savedPage * rowsShown;
var endItem = startItem + rowsShown;
$('.table tbody tr').slice(startItem, endItem).show();
// 标记对应页码为当前选中状态
$('.pagination-wrap li').eq(savedPage).addClass('is-current');

$('.pagination-wrap li').bind('click', function(){
    $('.pagination-wrap li').removeClass('is-current');
    $(this).addClass('is-current');
    var currPage = $(this).attr('rel');
    // 点击时保存当前页码到localStorage
    localStorage.setItem('currentPage', currPage);
    
    var startItem = currPage * rowsShown;
    var endItem = startItem + rowsShown;
    $('.table tbody tr').css('opacity','0.0').hide().slice(startItem, endItem).
    css('display','table-row').animate({opacity:1}, 300);
});

补充说明

  • localStorage的数据会一直保留在浏览器中,除非手动清除或用代码删除
  • 如果需要关闭标签页后就清除记忆,可以把localStorage换成sessionStorage,用法完全一致,只是sessionStorage在标签页关闭后会自动清空

内容的提问来源于stack exchange,提问作者user19818308

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 01:01:05