You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遍历服装产品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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:23:30