You need to enable JavaScript to run this app. 求助修复jQuery实现的卡片搜索过滤与分页功能异常问题
优惠活动
大模型
产品
解决方案
定价
更多

求助修复jQuery实现的卡片搜索过滤与分页功能异常问题

前端卡片分页+搜索功能修复方案

问题成因

  • 搜索逻辑与分页未联动:原代码搜索时直接展示所有符合条件的卡片,未基于过滤结果重算分页、触发分页渲染,导致结果不受每页9张的限制。
  • 分页箭头逻辑错误:原代码统一取分页按钮的文本转数字作为页码,左右箭头内为图标无文本,转换后得到NaN无法触发正确跳转。

修复后代码

JavaScript 部分

$(document).ready(function() {
  const pageSize = 9;
  let currentPage = 1;
  let filteredCards = [];

  // 搜索过滤逻辑
  $("#myInput").on("keyup", function() {
    const keyword = $(this).val().toLowerCase().trim();
    // 筛选符合关键词的卡片
    filteredCards = $(".card").filter(function() {
      return $(this).text().toLowerCase().indexOf(keyword) > -1;
    });
    currentPage = 1; // 搜索后重置到第一页
    renderPagination();
    showPage(currentPage);
  });

  // 动态渲染分页控件
  function renderPagination() {
    const totalPages = Math.ceil(filteredCards.length / pageSize) || 1;
    // 清空原有数字分页按钮,保留左右箭头
    $("#paginator a:not(:first-child):not(:last-child)").remove();
    // 生成对应数量的页码按钮,绑定data属性避免误选
    for (let i = 1; i <= totalPages; i++) {
      const $btn = $("<a href='#'></a>").text(i).attr("data-page", i);
      $("#paginator a:last-child").before($btn);
    }
    // 绑定数字页码点击事件
    $("#paginator a:not(:first-child):not(:last-child)").off("click").on("click", function(e) {
      e.preventDefault();
      currentPage = parseInt($(this).attr("data-page"));
      updateActiveStyle();
      showPage(currentPage);
    });
  }

  // 更新分页激活样式
  function updateActiveStyle() {
    $("#paginator a").removeClass("pagActive");
    $(`#paginator a[data-page="${currentPage}"]`).addClass("pagActive");
  }

  // 渲染当前页卡片
  function showPage(page) {
    $(".card").hide();
    filteredCards.each(function(index) {
      // 仅展示当前页区间内的过滤后卡片
      if (index >= pageSize * (page - 1) && index < pageSize * page) {
        $(this).show();
      }
    });
  }

  // 左箭头:跳第一页
  $("#paginator a:first-child").off("click").on("click", function(e) {
    e.preventDefault();
    currentPage = 1;
    updateActiveStyle();
    showPage(currentPage);
  });

  // 右箭头:跳最后一页
  $("#paginator a:last-child").off("click").on("click", function(e) {
    e.preventDefault();
    const totalPages = Math.ceil(filteredCards.length / pageSize) || 1;
    currentPage = totalPages;
    updateActiveStyle();
    showPage(currentPage);
  });

  // 初始化加载
  filteredCards = $(".card");
  renderPagination();
  showPage(currentPage);
});

CSS 部分

无需修改原有样式代码。

HTML 部分

无需修改原有页面结构。

核心调整说明

  • 新增filteredCards变量存储过滤后的卡片列表,分页逻辑完全基于该列表计算,避免全量数据和过滤结果混淆。
  • 搜索触发后自动重置页码到第一页,同时根据过滤结果总数动态调整分页按钮数量,保证分页数量匹配实际结果。
  • 拆分左右箭头和数字页码的点击逻辑,左右箭头分别绑定跳转第一页、最后一页的功能,不再依赖按钮文本转数字。
  • 所有分页点击事件新增e.preventDefault(),避免点击锚点时页面跳转。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.25 01:45:01