【问题标题】:get the .json to output on the HTML page using Javascript使用 Javascript 获取要在 HTML 页面上输出的 .json
【发布时间】:2020-08-07 02:25:18
【问题描述】:

Retrieve data from JSON file and display images in a gallery

我能够将 .json 文件输出到 HTML 页面上

@Jesuraja - 你是怎么做到的。 我实际上是在同一个状态。我有 JSON 文件,其图像本地驱动器位置与您的相似我想知道您是如何完成上述步骤的。 我只是想要一个方法我应该如何进行

【问题讨论】:

  • 为什么要编辑这个问题而不是关闭它?

标签: javascript html json image


【解决方案1】:

试试这个:

var jsonObj = {
"items": [
    {
      "url": "images/image_1.jpg",
      "caption": "Image 1 Caption"
    },
    {
      "url": "images/image_2.jpg.jpg",
      "caption": "Image 2 Caption"
    },
    {
      "url": "images/image_3.jpg.jpg",
      "caption": "Image 3 Caption"
    },
    {
      "url": "images/image_4.jpg.jpg",
      "caption": "Image 4 Caption"
    }
  ]
};

function createGallery(array) {
    // Create the list element:
    var list = document.createElement('ul');

    for(var i = 0; i < array.length; i++) {
        // Create the list item:
        var item = document.createElement('li');

        // Set its contents:
        item.appendChild(document.createTextNode("Image : "+array[i].url+"  Caption: "+array[i].caption));

        // Add it to the list:
        list.appendChild(item);
    }

    // Finally, return the constructed list:
    return list;
}

// Add the contents of options[0] to #foo:
document.getElementById('gallery').appendChild(createGallery(jsonObj.items));
&lt;div id="gallery"&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多