如何遍历API返回的50条商品数据并渲染为HTML列表li标签
商品列表渲染解决方案
修改说明
- 保留原有API调用逻辑,仅修改响应数据渲染部分
- 把给定的列表项模板抽离为JS模板字符串,保留所有原有样式类
- 遍历返回的商品数据,逐个替换模板内的占位符
- 所有渲染完成的列表项包裹在
<ul>标签内,整体插入到id为result的容器中
完整可运行代码
<div class="column right" id="result"> </div> <script type="text/javascript"> function callAliExpressApi(index) { let url = ''; if (index == 1) url = "/api/get-products"; else if (index == 2) url = "/api/get-hotproducts"; else if (index == 3) return; else if (index == 4) url = "/api/get-categories"; else if (index == 5) url = "/api/get-featuredpromo-info"; else if (index == 6) return; else if (index == 7) return; $.get(url, function(data, status){ // 商品列表项模板 const itemTemplate = ` <li class="layer-slide gallery-book-slide"> <div> <span class="gallery-book-list-img"> <img src="{productimage}"> </span> <div class="layer-region"> <a href="#" target="_blank"> <div class="layer-inner">{productname}</div> </a> </div> <a href="{producturl}" target="_blank" class="gallery-book-product-text" title="">{producttitle}</a> <div class="gallery-book-author" title=""></div> <div class=" gallery-book-product-price"> <div> <i> <span>¥</span>{productprice} </i> <span></span> </div> </div> </div> </li> ` let listContent = '<ul>' // 遍历商品数据替换占位符,若API返回的商品字段名不同,自行调整替换的对应字段即可 data.forEach(product => { let renderedItem = itemTemplate.replace('{productimage}', product.productimage) .replace('{productname}', product.productname) .replace('{producturl}', product.producturl) .replace('{producttitle}', product.producttitle) .replace('{productprice}', product.productprice) listContent += renderedItem }) listContent += '</ul>' $("#result").html(listContent); }); } </script>
效果参考

内容的提问来源于stack exchange,提问作者Shaiful Rizal Shaharudin
相关产品推荐
相关产品推荐

