如何使用js从json提取图片并在html标签中显示

时间:2018-10-15 17:28:26

标签: javascript html json leaflet

这是我的json:

var orgGuids = orgIds.ToDictionary(x => new Guid(x.Key), x => x.Value);

这是代码的一部分,试图在相对路径中提取图片,但它不起作用:

{ "type": "Feature", "properties": { **"pic": "/logo2.png",** "nombre": "T2V", "x": -4.45497, "y": 36.692029, "field_8": null, "field_9": null }, "geometry": { "type": "Point", "coordinates": [ -4.45497, 36.692029 ] } },

有人可以帮我举一些有关此操作的示例吗?

2 个答案:

答案 0 :(得分:1)

好的,您可以为img元素创建一个变量,然后将属性“ src”设置为指向json对象的相对或绝对路径。

var image = document.createElement('img');
image.setAttribute('src', json.properties.pic);

然后将元素插入所需的容器元素:

document.getElementById('img-container').appendChild(img);

答案 1 :(得分:0)

尚不清楚如何使用它,但这将处理您解析的数组(假设它是一个数组-我添加了另一个元素只是为了说明)

var pictures = [{
    "type": "Feature",
    "properties": {
      "pic": "/logo2.png",
      "nombre": "T2V",
      "x": -4.45497,
      "y": 36.692029,
      "field_8": null,
      "field_9": null
    },
    "geometry": {
      "type": "Point",
      "coordinates": [-4.45497, 36.692029]
    }
  },
  {
    "type": "Feature",
    "properties": {
      "pic": "/logo3.png",
      "nombre": "T3V",
      "x": -5.45497,
      "y": 35.692029,
      "field_8": null,
      "field_9": null
    },
    "geometry": {
      "type": "Point",
      "coordinates": [-4.45497, 35.692029]
    }
  }
];

for (var i = 0; i < pictures.length; i++) {
  var prop = pictures[i].properties
  console.log(prop.pic,"at:",prop.x,prop.y);
}