求助:如何用jQuery实现点击按钮分阶段批量显示.tmb元素
分批加载列表元素的实现方案
问题背景
页面结构:
<div class="uncode-post-table"> <div class="tmb">some content</div> <div class="tmb">some content</div> <!-- 总计50个.tmb元素,数量会随时间增加 --> </div> <a id="more-actions" onclick="event.preventDefault();" href="javascript:void(0);">Load more actions</a>
CSS默认仅显示前10个元素:
.uncode-post-table .tmb:nth-child(n+11) { display: none; }
现有点击事件会一次性显示所有隐藏元素,需求改为每次点击加载并显示接下来的10个元素,直到全部显示后隐藏加载按钮。
解决方案
替换原jQuery代码为以下实现:
let currentVisible = 10; const itemsPerBatch = 10; $("#more-actions").on("click", function() { const nextBatchEnd = currentVisible + itemsPerBatch; // 选中当前需显示的下一批元素并设置显示 $(".uncode-post-table .tmb").slice(currentVisible, nextBatchEnd).css("display", "block"); currentVisible = nextBatchEnd; const totalItems = $(".uncode-post-table .tmb").length; // 全部显示后隐藏加载按钮 if (currentVisible >= totalItems) { $(this).hide(); } });
关键逻辑说明
currentVisible追踪已显示的元素数量,初始值匹配CSS默认显示的10个slice()方法精准选取下一批需要显示的元素(左闭右开特性刚好覆盖接下来的10个)- 每次点击后更新已显示数量,实时检查是否已显示全部元素,满足条件则隐藏加载按钮
- 自适应元素数量变化:每次都会重新获取总元素数,即使后续.tmb元素新增也能正常工作
内容的提问来源于stack exchange,提问作者CliffVandyck
相关产品推荐
相关产品推荐

