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

Fetch JSON渲染页面内容不显示:HTML存在但无视觉效果求助

问题排查与修复方案

核心问题1:HTML拼接导致DOM结构无效

你的loadPictures函数中,.join("\"")用双引号作为数组元素的分隔符,会让生成的HTML片段之间插入多余的双引号,破坏DOM结构——浏览器无法解析带无效引号的HTML,所以页面看不到内容,但开发者工具能显示原始字符串内容。

修复方法:
将.join("\"")改为.join('')(用空字符串分隔),确保拼接出连续有效的HTML:

const loadPictures = (picturesArr) => {
  paintingSection.innerHTML = picturesArr
    .map(
      (picture) =>
        `
<div class="painting-container ${picture.align} scroll-hidden">
  <div class="text-container">
    <h3 class="absolute pain-head">${picture.heading}</h3>
    <p class="absolute pain-info">${picture.description}</p>
  </div>
    <img
      src="../../media/obrazy/v-zajeti-barev-2/${picture.fileName}"
      alt="${picture.alt}"
      class="painting"
    />
</div>
`
    )
    .join('');
};

核心问题2:代码中多余的转义引号

多处不必要的转义引号会引发语法错误或逻辑异常,需修正:

  • document.querySelector("\".painting-div-container\"") → document.querySelector(".painting-div-container")
  • fetch("\"./paintings.json\"") → fetch("./paintings.json")
  • throw new Error("\"Network response was not ok \" + response.statusText); → throw new Error("Network response was not ok " + response.statusText);
  • console.error("\"Error fetching the JSON file:\", error); → console.error("Error fetching the JSON file:", error);

核心问题3:JSON文件格式错误

你提供的JSON文件中所有引号都加了转义\",这不符合标准JSON格式,会导致解析失败(若实际文件如此)。正确的JSON需去掉转义:

[
  {
    "heading": "A jako Anděl - 2013",
    "description": "akryl na šepsované desce, 50x60",
    "fileName": "A-JAKO-ANDĚL.jpg",
    "alt": "A jako anděl - obraz",
    "align": "vert"
  },
  {
    "heading": "Barevná láska - 2013",
    "description": "akryl na plátně, 100x130",
    "fileName": "Barevná-láska-2.jpg",
    "alt": "Barevná láska 2 - obraz",
    "align": "hori"
  }
]

其他模块img未定义的解决方法

fetch是异步操作,其他模块可能在HTML生成前就尝试访问img元素,导致报错。解决思路:

  • 将依赖img的代码放到loadPictures执行完成后调用,比如在fetch的第二个then中:
fetch("./paintings.json")
  .then((response) => {
    if (!response.ok) {
      throw new Error("Network response was not ok " + response.statusText);
    }
    return response.json();
  })
  .then((data) => {
    loadPictures(data);
    // 在这里调用依赖img的其他模块初始化代码
    initImageRelatedModules();
  })
  .catch((error) => {
    console.error("Error fetching the JSON file:", error);
  });
  • 或者用MutationObserver监听paintingSection的DOM变化,当内容插入后再初始化相关代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 14:04:50