如何实现每输出3条数据切换div、每6条数据再次切换div?
解决方案:按数据条数动态切换容器
嘿,我来帮你搞定这个按数据条数切换容器的需求!根据你描述的“每输出3条数据切换至新div,每6条切换至另一个div”,结合你给出的HTML结构,我理解的是:每3个产品卡片放在一个.row容器里,每2个.row(也就是6条数据)放在一个.mySlides容器里。下面是具体的实现方案:
前端JavaScript动态渲染方案
如果你的产品数据是前端获取的(比如从API或者本地数组),可以用JS来分组生成HTML:
1. 准备数据源
首先定义你的产品数据数组:
const products = [ { img: "Image/2.jpg", price: "Rp.5000 / ikat" }, { img: "Image/3.jpg", price: "Rp.9000 / ikat" }, { img: "Image/4.jpg", price: "Rp.6000 / ikat" }, { img: "Image/5.jpg", price: "Rp.7000 / ikat" }, { img: "Image/6.jpg", price: "Rp.8000 / ikat" }, { img: "Image/7.jpg", price: "Rp.10000 / ikat" }, { img: "Image/8.jpg", price: "Rp.12000 / ikat" }, // 可以继续添加更多产品数据 ];
2. 编写渲染函数
这个函数会自动按规则分组并生成对应的HTML结构:
function renderProducts(products) { let finalHtml = ''; // 外层循环:每6条数据生成一个 .mySlides 容器 for (let i = 0; i < products.length; i += 6) { const slideProducts = products.slice(i, i + 6); finalHtml += '<div class="w3-content w3-display-container mySlides">'; // 内层循环:每3条数据生成一个 .row 容器 for (let j = 0; j < slideProducts.length; j += 3) { const rowProducts = slideProducts.slice(j, j + 3); finalHtml += '<div class="row">'; // 遍历当前row的产品,生成卡片 rowProducts.forEach(product => { finalHtml += ` <div class="col-4"> <img src="${product.img}" class="gbr"/> <span>${product.price}</span> <button class="tengbr">Beli</button> </div> `; }); finalHtml += '</div>'; // 闭合当前 .row } finalHtml += '</div>'; // 闭合当前 .mySlides } // 将生成的HTML插入到页面的目标容器中(比如你可以先在页面加一个id为product-wrap的容器) document.getElementById('product-wrap').innerHTML = finalHtml; } // 调用函数渲染产品 renderProducts(products);
后端PHP渲染方案
如果你的数据是后端生成的,用PHP也可以实现同样的逻辑:
<?php // 产品数据源 $products = [ ['img' => 'Image/2.jpg', 'price' => 'Rp.5000 / ikat'], ['img' => 'Image/3.jpg', 'price' => 'Rp.9000 / ikat'], ['img' => 'Image/4.jpg', 'price' => 'Rp.6000 / ikat'], ['img' => 'Image/5.jpg', 'price' => 'Rp.7000 / ikat'], ['img' => 'Image/6.jpg', 'price' => 'Rp.8000 / ikat'], ['img' => 'Image/7.jpg', 'price' => 'Rp.10000 / ikat'], // 更多产品数据... ]; $outputHtml = ''; $totalProducts = count($products); // 每6条数据生成一个 .mySlides 容器 for ($i = 0; $i < $totalProducts; $i += 6) { $currentSlideProducts = array_slice($products, $i, 6); $outputHtml .= '<div class="w3-content w3-display-container mySlides">'; $slideProductCount = count($currentSlideProducts); // 每3条数据生成一个 .row 容器 for ($j = 0; $j < $slideProductCount; $j += 3) { $currentRowProducts = array_slice($currentSlideProducts, $j, 3); $outputHtml .= '<div class="row">'; foreach ($currentRowProducts as $product) { $outputHtml .= '<div class="col-4"> <img src="' . $product['img'] . '" class="gbr"/> <span>' . $product['price'] . '</span> <button class="tengbr">Beli</button> </div>'; } $outputHtml .= '</div>'; } $outputHtml .= '</div>'; } // 输出最终HTML echo $outputHtml; ?>
逻辑说明
- 外层循环按6条数据为一组,创建最外层的
.mySlides容器 - 每个
.mySlides内部,按3条数据为一组,创建.row容器 - 每个
.row里放置3个产品卡片(.col-4),完全匹配你给出的HTML结构
这样就能严格满足你“每3条换一个div,每6条换另一个div”的需求啦!
内容的提问来源于stack exchange,提问作者Eric Anthony Wu
相关产品推荐
相关产品推荐

