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

求助:通过JavaScript读取JSON文件在HTML中显示图片仅显示路径

解决图片仅显示路径不显示图片的问题

问题核心是你当前只是把图片路径作为文本插入到了<div data-photo>中,而非创建<img>元素并设置其src属性来加载图片。以下是具体修复方案:

方案一:修改HTML模板+更新JavaScript

1. 调整HTML模板

在data-post-template的data-photo容器内添加<img>标签,用于承载图片:

<template data-post-template>
  <div class="card">
    <div class="header" data-header></div>
    <div class="body" data-body></div>
    <div class="photo" data-photo>
      <img data-img alt="博客文章缩略图">
    </div>
  </div>
</template>

2. 更新JavaScript代码

将设置文本的逻辑改为设置<img>的src属性:

fetch("../jsn/posts-main.json")
  .then(res => res.json())
  .then(data => {
    posts = data.map(post => {
      const card = postCardTemplate.content.cloneNode(true).children[0]
      const header = card.querySelector("[data-header]")
      const body = card.querySelector("[data-body]")
      const imgElement = card.querySelector("[data-img]")
      header.textContent = post.title
      body.textContent = post.text
      imgElement.src = post.img
      postCardContainer.append(card)
      return { title: post.title, element: card }
    })
})

方案二:仅修改JavaScript(无需改动HTML模板)

如果不想调整HTML模板,可直接在data-photo容器内动态创建<img>元素:

fetch("../jsn/posts-main.json")
  .then(res => res.json())
  .then(data => {
    posts = data.map(post => {
      const card = postCardTemplate.content.cloneNode(true).children[0]
      const header = card.querySelector("[data-header]")
      const body = card.querySelector("[data-body]")
      const photoContainer = card.querySelector("[data-photo]")
      header.textContent = post.title
      body.textContent = post.text
      
      // 动态创建img元素并设置属性
      const imgElement = document.createElement('img')
      imgElement.src = post.img
      imgElement.alt = `${post.title} 缩略图`
      photoContainer.appendChild(imgElement)
      
      postCardContainer.append(card)
      return { title: post.title, element: card }
    })
})

额外注意事项

  • 检查相对路径正确性:JSON中的../assets/images/recipes/Madeleines.png需匹配HTML文件到图片的层级,若HTML在根目录,路径应改为assets/images/recipes/Madeleines.png(去掉../)。
  • 外部链接测试:JSON中的https://pbs.twimg.com/...类外部链接若无法显示,需检查链接是否失效或浏览器是否有跨域限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 16:48:16