遍历服装产品JSON文件,检查标题含特定词的jQuery实现问询
解决服装产品JSON遍历与特定词汇匹配问题
我来帮你补全未完成的bought_together部分代码,同时梳理整个逻辑的核心要点,让功能完整跑起来:
// 异步加载服装产品JSON数据 $.getJSON('test.json', function(data) { // 遍历主产品列表 $.each(data.products, function(index, product) { // 匹配标题含"t-shirt"的产品(忽略大小写) if (product.title.toLowerCase().includes('t-shirt')) { // 生成图片元素并追加到指定容器 const shirtImg = $('<img>') .attr('src', product.image_url) .attr('alt', product.title) .addClass('product-img'); // 可自定义样式类 $('.TopsImages').append(shirtImg); } // 处理"关联购买"的产品列表(补全逻辑) if (product.bought_together && product.bought_together.length > 0) { $.each(product.bought_together, function(_, relatedItem) { // 匹配标题含"sandal"的关联产品(同样忽略大小写) if (relatedItem.title.toLowerCase().includes('sandal')) { // 生成图片并追加到对应容器(这里假设用.SandalsImages,可按需修改) const sandalImg = $('<img>') .attr('src', relatedItem.image_url) .attr('alt', relatedItem.title) .addClass('related-product-img'); $('.SandalsImages').append(sandalImg); } }); } }); });
关键细节说明:
- 大小写兼容:用
toLowerCase()把标题统一转成小写,再用includes()匹配,避免因为标题里的大写(比如"T-Shirt")导致匹配失败 - 空值防护:处理
bought_together时先判断是否存在且有数据,防止数组为空或字段不存在时报错 - 可扩展性:给图片添加自定义样式类,方便后续通过CSS调整展示效果
额外优化建议:
如果担心JSON加载失败,可以加上错误处理逻辑,方便排查问题:
$.getJSON('test.json') .done(function(data) { // 上面的产品处理逻辑 }) .fail(function(jqxhr, textStatus, error) { console.error('JSON加载失败:', textStatus, error); });
内容的提问来源于stack exchange,提问作者Jake123
相关产品推荐
相关产品推荐

