首页 > 解决方案 > 如何编写 JavaScript 代码以访问 JSON 文件中的图像?

问题描述

我应该创建一个循环来输出几个带有样式的图像。我在使用正确的语法和图像路径时遇到问题。

我尝试过使用相对路径(请参见下面的 JavaScript 文件)执行此操作,但我仍然看不到 html 上图像的输出。

这是我的 JSON 文件 (photos.json)

const content = `
{
      "id":"3a5c5da5-5a12-4d2b-b0dd-abc28eaf810b",
      "title":"British Museum",
      "description":"The library in the British Museum in London. The British Museum Reading Room, situated in the centre of the Great Court of the British Museum, used to be the main reading room of the British Library. In 1997, this function moved to the new British Library building at St Pancras, London, but the Reading Room remains in its original form at the British Museum.",
      "location":{
         "iso":"GB",
         "country":"United Kingdom",
         "city":"London",
         "cityCode":2643743,
         "continent":"EU",
         "latitude":51.519148,
         "longitude":-0.126826
      },
      "filename":"5855729828.jpg",
      "colors":[
         {
            "hex":"#a9b490",
            "name":"Norway"
         },
         {
            "hex":"#bab984",
            "name":"Pine Glade"
         },
         {
            "hex":"#71735c",
            "name":"Finch"
         },
         {
            "hex":"#332625",
            "name":"Wood Bark"
         },
         {
            "hex":"#b99a5d",
            "name":"Barley Corn"
         }
      ]
   }
...

这是我的 HTML 文件。而且我不应该在这个文件中添加任何东西。

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8">
   <title>Lab 8</title>
   <link href="https://fonts.googleapis.com/css?family=Oswald:300,500" rel="stylesheet">   
   <link rel="stylesheet" type="text/css" href="css/lab08.css" />


</head>
<body>
<main id="test4">
  <header>
    <h1>Test Your Knowledge #4</h1>
  </header>  
  <section>
      <script src="js/photos.json"></script>
      <script src="js/lab08-test04.js"></script>

  </section>
</main>
</body>
</html>

到目前为止,这是我的 Javascript 文件...... html 在主文件夹中,图像在另一个名为“images”的文件夹中,所以我尝试使用 images/img.jpg 路径在 JavaScript 上获取图像但失败了,请帮忙。

const photos = JSON.parse(content);

document.write('<img src="' + photos[0].filename + '">');

这不起作用,但这段代码可以,但我不想这样做,因为我必须使用循环:

document.write('<img src="images/5855729828.jpg">');

谢谢!

标签: javascripthtmljsonoutput

解决方案


试试这个:在 Html 文件中添加:<img src="" id="imgtag" /> 并在 js 文件中添加以下代码:

const imgtag = document.querySelector("#imgtag");
imgtag.src = content.filename

推荐阅读