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

使用JavaScript slice方法实现单文件商品列表分页

商品列表分页实现方案

需求说明

给定如下商品数组:

let products = {
    data: [
      { productName: "Product1" },
      { productName: "Product2" },
      { productName: "Product3" },
      { productName: "Product4" },
      { productName: "Product5" },
      // 更多商品对象...
    ]
};

需要实现:

  • 遍历展示所有商品,每10个分为一页
  • 初始加载显示第一页(前10个商品)
  • 提供分页切换按钮,支持上下页跳转
  • 所有逻辑在单个HTML文件内完成,通过循环自动生成分页内容,无需手动创建页面

完整实现代码

把以下代码保存为单个HTML文件即可运行:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品分页展示</title>
    <style>
        .product-container {
            max-width: 1200px;
            margin: 20px auto;
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
        }
        .product-item {
            padding: 15px;
            border: 1px solid #eee;
            border-radius: 8px;
            text-align: center;
        }
        .pagination {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            gap: 8px;
            justify-content: center;
            padding: 20px 0;
        }
        .pagination button {
            padding: 8px 16px;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
        }
        .pagination button:disabled {
            cursor: not-allowed;
            background-color: #f5f5f5;
            color: #999;
        }
    </style>
</head>
<body>
    <div class="product-container" id="productContainer"></div>
    <div class="pagination">
        <button id="prevBtn">上一页</button>
        <span id="pageInfo"></span>
        <button id="nextBtn">下一页</button>
    </div>

    <script>
        // 模拟商品数据,可替换为实际数据
        let products = {
            data: Array.from({length: 35}, (_, i) => ({ productName: `Product${i+1}` }))
        };

        // 分页配置
        const itemsPerPage = 10;
        let currentPage = 1;
        const totalPages = Math.ceil(products.data.length / itemsPerPage);

        // 渲染当前页商品
        function renderProducts() {
            const container = document.getElementById('productContainer');
            container.innerHTML = '';
            
            // 计算当前页的商品起始和结束索引
            const startIndex = (currentPage - 1) * itemsPerPage;
            const endIndex = Math.min(startIndex + itemsPerPage, products.data.length);
            const currentProducts = products.data.slice(startIndex, endIndex);

            // 循环生成商品元素
            currentProducts.forEach(product => {
                const item = document.createElement('div');
                item.className = 'product-item';
                item.textContent = product.productName;
                container.appendChild(item);
            });

            // 更新页码信息
            document.getElementById('pageInfo').textContent = `第 ${currentPage} 页 / 共 ${totalPages} 页`;
            
            // 控制按钮禁用状态
            document.getElementById('prevBtn').disabled = currentPage === 1;
            document.getElementById('nextBtn').disabled = currentPage === totalPages;
        }

        // 绑定按钮事件
        document.getElementById('prevBtn').addEventListener('click', () => {
            if (currentPage > 1) {
                currentPage--;
                renderProducts();
            }
        });

        document.getElementById('nextBtn').addEventListener('click', () => {
            if (currentPage < totalPages) {
                currentPage++;
                renderProducts();
            }
        });

        // 初始渲染第一页
        renderProducts();
    </script>
</body>
</html>

关键逻辑说明

  • 分页核心计算:通过(currentPage - 1) * itemsPerPage计算当前页商品的起始索引,用slice()方法截取对应区间的商品数据
  • 动态渲染:每次切换页面时清空容器,循环当前页的商品数据生成DOM元素并插入容器
  • 按钮状态控制:根据当前页是否为第一页/最后一页,自动禁用对应的上一页/下一页按钮,避免无效点击
  • 页码信息实时更新:显示当前页码和总页数,让用户清晰了解分页状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 11:46:05