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

PrestaShop中Infinite Scroll已展示商品数与总数同步问题

解决PrestaShop中Infinite Scroll无限滚动的已加载商品数同步显示问题

核心思路

Smarty是服务端渲染变量,页面加载后无法直接修改,因此需要:

  1. 将初始的商品总数和已展示数从Smarty变量提取到前端,用JS维护计数
  2. 利用Infinite Scroll的append事件(每次加载新商品后触发)更新计数并同步到DOM

步骤1:修改Smarty模板,便于JS操作

先给计数数字添加独立容器,方便后续替换内容:

{* 商品计数显示 *}
<p class="items-shown">
  {l s='You have seen' d='Shop.Theme.Global'} 
  <span class="current-shown">{$listing.pagination['items_shown_to']}</span> 
  {l s='products of' d='Shop.Theme.Global'} 
  <span class="total-items">{$listing.pagination['total_items']}</span>
</p>

{* 加载更多按钮 *}
<button class="infinite-scroll-button">
  {l s='See more' d='Shop.Theme.Actions'}
</button>

步骤2:编写JS逻辑同步计数

初始化Infinite Scroll并监听加载事件,更新计数:

// 1. 获取初始计数和DOM元素
const currentShownEl = document.querySelector('.current-shown');
const totalItemsEl = document.querySelector('.total-items');
let currentCount = parseInt(currentShownEl.textContent);
const totalCount = parseInt(totalItemsEl.textContent);

// 2. 初始化Infinite Scroll(替换为你项目的实际选择器)
const infScroll = new InfiniteScroll('.product-listing-wrapper', {
  path: '.pagination-next', // 分页下一页的链接选择器
  button: '.infinite-scroll-button', // 加载按钮选择器
  append: '.product-item', // 单个商品项的选择器
});

// 3. 监听新商品加载完成事件,更新计数
infScroll.on('append', function(response, path, items) {
  // 计算本次加载的商品数量
  const addedCount = items.length;
  // 更新当前计数(不超过总数)
  currentCount = Math.min(currentCount + addedCount, totalCount);
  // 同步到页面显示
  currentShownEl.textContent = currentCount;

  // 加载完成后隐藏按钮(可选)
  if (currentCount >= totalCount) {
    document.querySelector('.infinite-scroll-button').style.display = 'none';
  }
});

关键说明

  • 替换代码中的选择器(.product-listing-wrapper、.pagination-next、.product-item)为你项目中实际的DOM选择器
  • 多语言文本由Smarty提前渲染,JS仅负责更新数字部分,无需处理语言切换逻辑
  • append事件是Infinite Scroll内置的钩子,每次成功加载并追加新内容后触发,适合用来同步计数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 05:20:27