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

如何用JavaScript的map函数将API的JSON数据仅渲染标题与图片到HTML容器?

可以用JavaScript的map函数仅展示标题和图片内容

完全可以通过map函数筛选并渲染仅包含标题和图片的内容,以下是具体实现步骤:

1. 确认API返回数据格式

先确保API返回的是数组格式(如果是单个对象,可手动包装为数组),完整返回示例参考:

[
  {
    "title": "Dungeon Meshi",
    "id": "dungeon-meshi",
    "image_url": "https://gogocdn.net/cover/dungeon-meshi-1704169699.png",
    "released": "2024"
  }
]

2. 编写JavaScript渲染逻辑

通过fetch获取数据后,用map遍历数据生成仅包含图片和标题的HTML结构,再插入到目标容器中:

// 假设目标容器的选择器为 .popular-container
const container = document.querySelector('.popular-container');

// 请求API数据
fetch('https://api-amvstrm.nyt92.eu.org/api/v1/popular')
  .then(res => res.json())
  .then(data => {
    // 用map生成每个项的HTML片段
    const itemsHtml = data.map(item => `
      <div class="col-lg-4 col-md-6 col-sm-6">
        <div class="product__item">
          <div class="product__item__pic set-bg" data-setbg="${item.image_url}"></div>
          <div class="product__item__text">
            <h5><a href="#">${item.title}</a></h5>
          </div>
        </div>
      </div>
    `).join(''); // 将数组转为完整HTML字符串

    // 插入到页面容器中
    container.innerHTML = itemsHtml;
  })
  .catch(err => console.error('数据请求失败:', err));

逻辑说明

  • 移除了原HTML中无关的ep、comment、view标签以及ul状态列表,只保留图片容器和标题链接。
  • map函数负责遍历每一条数据,生成对应的HTML字符串片段,最后通过join('')合并成完整代码插入页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 16:33:12