使用Fetch动态生成独立商品卡片时内容全部写入同一div问题求助
问题原因
每次循环中调用document.querySelector(".product-card")时,该方法默认匹配页面内第一个符合类名的div元素,导致所有后续生成的子元素都被插入到第一次循环创建的商品卡片中,后续新建的product-card均为空。
修正后代码
main(); function main() { const getJsonData = fetch('http://localhost:3000/api/cameras') .then(response => response.json()); getJsonData .then(function(dispatchData) { // 父容器仅需查询一次,无需放入循环重复执行 const getPrincipalContainer = document.getElementById("products"); for (let item in dispatchData) { /*创建商品卡片容器*/ const createCard = document.createElement("div") createCard.className = 'product-card'; getPrincipalContainer.append(createCard) /*直接向当前新建的卡片插入内容,无需再次查询DOM*/ // 插入商品图片 const createImg = document.createElement("img") createImg.className = "card-img-top"; createImg.src = dispatchData[item].imageUrl createCard.appendChild(createImg) // 插入商品名称 const createName = document.createElement("h2") createName.className = "card-title" createName.innerText = dispatchData[item].name createCard.appendChild(createName) // 插入商品价格 const createPrice = document.createElement("p") createPrice.className = "product-price" createPrice.innerText = dispatchData[item].price createCard.appendChild(createPrice) // 插入商品详情链接 const createLink = document.createElement("a") createLink.className = "product-sheet-link" createLink.innerText = "Voir la fiche produit" createCard.appendChild(createLink) } }) }
优化说明
- 父容器DOM查询移出循环,避免重复查询带来的性能损耗
- 直接复用刚创建的
createCard元素插入子节点,既解决了元素匹配错误的问题,也进一步提升了代码执行效率
内容的提问来源于stack exchange,提问作者El_Michel
相关产品推荐
相关产品推荐

