You need to enable JavaScript to run this app. 分页功能无法跳转光标至当前页且显示额外页码故障求助
优惠活动
大模型
产品
解决方案
定价
更多

分页功能无法跳转光标至当前页且显示额外页码故障求助

问题1:生成多余页码的修复

问题原因:当前pageIndex方法中拼接pageOne、pageTwo、pageThree三个子函数的页码生成逻辑缺少边界校验,没有限制输出的页码范围,导致当前页为3时错误输出了预期外的页码5。

修复方案:

重新设计页码生成逻辑,按照如下规则生成页码:

  1. 以当前页为中心,前后各展示1个相邻页码,连续展示的页码总长度不超过4个
  2. 当连续页码起始值大于2时,前面加1..缩略展示超出范围的前序页码
  3. 所有生成的页码做范围校验,超出当前连续区间外的页码不生成
    参考修改代码:
public static String pageIndex(int currentPage, String url, int lastPage) {
    StringBuilder page = new StringBuilder();
    // 计算连续展示的页码区间
    int start = Math.max(2, currentPage - 1);
    int end = Math.min(lastPage, currentPage + 1);
    // 拼接上一页按钮
    if(currentPage > 1) {
        page.append("<a href=\"").append(url).append("?page=").append(currentPage-1).append("\">Previous</a> ");
    }
    // 拼接首位页码和省略号
    if(start > 1) {
        page.append("<a href=\"").append(url).append("?page=1\">1</a>");
        if(start > 2) {
            page.append(".. ");
        } else {
            page.append(" ");
        }
    }
    // 拼接连续页码段
    for(int i = start; i <= end; i++) {
        if(i == currentPage) {
            // 当前页加粗,添加自动聚焦属性
            page.append("<strong autofocus>").append(i).append("</strong> ");
        } else {
            page.append("<a href=\"").append(url).append("?page=").append(i).append("\">").append(i).append("</a> ");
        }
    }
    // 拼接下一页按钮
    if(currentPage < lastPage) {
        page.append("<a href=\"").append(url).append("?page=").append(currentPage+1).append("\">Next</a>");
    }
    return page.toString();
}

问题2:光标未跳转至对应页码位置的修复

问题原因:当前生成的当前页元素没有配置自动聚焦逻辑,页面刷新后不会自动定位到当前页码对应的元素上。

修复方案:

二选一实现即可:

  1. 生成当前激活页码的HTML元素时,直接添加autofocus原生属性,页面加载后会自动聚焦到该元素(上述修改代码中已加入该属性)
  2. 页面加载完成后执行JS代码,选中当前页对应的元素调用focus()方法完成聚焦:
window.onload = function() {
    // 选择器根据实际页面的当前页元素标签、类名调整
    document.querySelector('strong').focus();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 02:36:04