如何用JavaScript基于对象数组实现每页展示10条数据的轮播器
代码调整方案
核心修改逻辑如下:
- 定义单页展示数量常量,使用
Array.slice()根据当前激活的轮播索引切割数组,每次仅取当前页需要的10条数据 - 删除原代码中冗余的嵌套循环逻辑,避免重复渲染全量数组数据
- 每次渲染绑定当前激活的轮播页容器,而非固定仅渲染第一页容器
修改后的完整JavaScript代码如下(HTML代码无需改动):
const slidesShop = document.querySelectorAll('.slide-shop'); const slider = document.querySelector('.slider-shop'); const prev = document.getElementById('prev'); const next = document.getElementById('next'); // 全量自行车数据,替换为你实际的完整数组即可 const bikes = [ { name: 'Trek', size: 'L', type: 'Mountain Bike', price: 1000, text_line: 'Bike rides bike of the same something, some, someone!Best with there opinion', }, { name: 'Trek', size: 'XL', type: 'Mountain Bike', price: 1000, text_line: 'Bike rides bike of the same something, some, someone!Best with there opinion', } // 其余数据继续补充即可 ] let activeSlide = 0; const PER_PAGE = 10; // 单页展示10条 const changeSlide = () => { slidesShop.forEach((page) => { page.classList.remove('active-1'); slidesShop[activeSlide].classList.add('active-1'); }); }; prev.addEventListener('click', () => { activeSlide--; if (activeSlide < 0) { activeSlide = slidesShop.length - 1; } changeSlide(); showBikes(); }); next.addEventListener('click', () => { activeSlide++; if (activeSlide > slidesShop.length - 1) { activeSlide = 0; } changeSlide(); showBikes(); }); const showBikes = () => { // 计算当前页数据的起止索引 const startIndex = activeSlide * PER_PAGE; const endIndex = startIndex + PER_PAGE; // 切割得到当前页需要展示的10条数据 const currentPageBikes = bikes.slice(startIndex, endIndex); // 拿到当前激活的轮播页容器 const currentSlide = slidesShop[activeSlide]; currentSlide.innerHTML = ''; // 遍历当前页数据渲染,无需嵌套循环 currentPageBikes.forEach((bike) => { const { name, size, type, price, text_line } = bike; const slideShopItem = document.createElement('div'); slideShopItem.classList.add('slide-shop-item'); slideShopItem.innerHTML = ` <img src="img/about.jpg" alt="" /> <div class="item-content"> <h3>${name}</h3> <p> ${text_line} </p> <small>Size: <span>${size}</span></small> <small>Type: <span>${type}</span></small> <small>Price: <span>${price}$</span></small> </div> `; currentSlide.appendChild(slideShopItem); }); }; // 初始化渲染第一页数据 showBikes();
补充说明:如果后续需要扩展轮播页数,只需要在HTML的.slider-shop容器内新增对应数量的.slide-shop节点即可,JS逻辑无需修改,会自动适配轮播页数。
内容的提问来源于stack exchange,提问作者Nikola Maricic
相关产品推荐
相关产品推荐

