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

如何用循环在本地站点展示JSON中所有物品名称与图片?

问题原因分析

你遇到的问题很典型:页面上的<img id="outputIconURL">和<p id="outputName">是唯一的DOM元素,每次循环时你都在覆盖它们的src和innerHTML属性,所以循环结束后,页面只会显示最后一次循环的内容。而控制台能打印所有数据,是因为console.log不会覆盖之前的输出,只是追加打印。

解决方案:动态创建元素展示所有物品

我们需要为每个物品创建独立的图片和名称元素,然后把它们添加到页面的容器中。下面提供两种常用的实现方式:

方式1:使用jQuery模板字符串拼接(简洁高效)

首先修改HTML结构,替换原来的固定img和p为一个容器:

<body>
  <div id="inventory-container"></div>
  <!-- 其他脚本不变 -->
</body>

然后修改AJAX的success回调函数:

success: function(data){
  // 获取容器元素
  const inventoryContainer = $('#inventory-container');
  
  // 遍历所有物品
  $(data.data.steam_inventory.items).each(function(index, value){
    const marketName = value.market_hash_name;
    const imageUrl = value.image;
    
    // 拼接每个物品的HTML结构
    const itemHtml = `
      <div class="inventory-item" style="margin: 15px 0;">
        <img src="${imageUrl}" width="350" height="300" alt="${marketName}">
        <p>${marketName}</p>
      </div>
    `;
    
    // 将新创建的物品元素追加到容器中
    inventoryContainer.append(itemHtml);
    
    console.log(marketName, "\n", imageUrl);
  });
}

方式2:原生JavaScript创建DOM元素(更灵活)

如果你不想依赖jQuery的语法,也可以用原生JS实现:

success: function(data){
  const inventoryContainer = document.getElementById('inventory-container');
  const items = data.data.steam_inventory.items;
  
  items.forEach(function(item){
    const marketName = item.market_hash_name;
    const imageUrl = item.image;
    
    // 创建包裹每个物品的div
    const itemWrapper = document.createElement('div');
    itemWrapper.style.margin = '15px 0';
    
    // 创建图片元素
    const itemImage = document.createElement('img');
    itemImage.src = imageUrl;
    itemImage.width = 350;
    itemImage.height = 300;
    itemImage.alt = marketName;
    
    // 创建名称段落
    const itemName = document.createElement('p');
    itemName.textContent = marketName;
    
    // 组装元素并添加到容器
    itemWrapper.appendChild(itemImage);
    itemWrapper.appendChild(itemName);
    inventoryContainer.appendChild(itemWrapper);
    
    console.log(marketName, "\n", imageUrl);
  });
}
补充说明
  • 两种方式的核心逻辑都是为每个物品生成独立的DOM元素,避免覆盖原有内容;
  • 你可以给.inventory-item添加CSS样式,让物品展示更美观(比如横向排列、添加边框等);
  • 注意使用alt属性为图片添加替代文本,提升可访问性。

内容的提问来源于stack exchange,提问作者Temi1337

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:54:10