如何通过循环遍历JSON数组生成多个商品卡片?
如何循环批量生成商品卡片?
你可以通过以下几种循环方式遍历商品数组,结合现有代码批量生成卡片,以下是适配你代码的改造方案:
1. 使用 Array.forEach()(最简洁推荐)
这是数组遍历的常用方法,代码可读性高,完全适配你的场景:
// 假设product是挂载卡片的容器元素,比如document.getElementById('product-container') Produits.forEach(item => { // 兼容价格字段大小写(第一个商品是Price大写,其余是price小写) const productPrice = item.price || item.Price; // 计算折扣后价格(按需使用) const finalPrice = productPrice * (1 - item.reduction / 100); const wrapper = document.createElement('div'); // 修正原代码错误:createElement仅接受标签名,用innerHTML渲染完整卡片结构 wrapper.innerHTML = ` <div class="grid-item-product"> <img src="${item.img}" alt="${item.id}"> <div class="card-content"> <button id="control-price-${item.id}"> <i class="fa-sharp fa-solid fa-pen"></i> </button> <h3>${item.title}</h3> <span>起售价 <strong id="price-${item.id}">${finalPrice.toFixed(2)} €</strong></span> </div> </div> `; product.appendChild(wrapper.firstElementChild); });
2. 使用 for...of 循环(支持中断场景)
如果需要中途终止循环,这种方式更灵活:
// 假设product是挂载卡片的容器元素 for (const item of Produits) { const productPrice = item.price || item.Price; const finalPrice = productPrice * (1 - item.reduction / 100); const wrapper = document.createElement('div'); wrapper.innerHTML = ` <div class="grid-item-product"> <img src="${item.img}" alt="${item.id}"> <div class="card-content"> <button id="control-price-${item.id}"> <i class="fa-sharp fa-solid fa-pen"></i> </button> <h3>${item.title}</h3> <span>起售价 <strong id="price-${item.id}">${finalPrice.toFixed(2)} €</strong></span> </div> </div> `; product.appendChild(wrapper.firstElementChild); }
重要注意事项
- 修正DOM创建逻辑:
document.createElement()仅接受单个标签名(如div),不能直接传入完整模板字符串,改用innerHTML渲染卡片结构更合理。 - 统一属性格式:商品数组中第一个条目的价格字段是
Price(大写P),其余为price,必须做兼容处理防止读取失败。 - 保证ID唯一性:按钮和价格标签的ID不能硬编码为固定值,要绑定商品的
id(如control-price-${item.id}),避免重复ID引发的DOM操作问题。 - 可选优化:如果需要展示折扣后价格,可通过
price * (1 - reduction/100)计算,并使用toFixed(2)保留两位小数保证格式统一。
内容的提问来源于stack exchange,提问作者manu974proDev
相关产品推荐
相关产品推荐

