首页 > 解决方案 > 如何使用js从json中提取图片并显示在html标签中

问题描述

这是我的json:

{ "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 ] } },

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

var info = L.control();
info.onAdd = function (map) {
    this._div = L.DomUtil.create('div', 'info');
    this.update();
    return this._div;
};
info.update = function (props) {
    // console.log(props);
    this._div.innerHTML = ''
    +(props? '<b><center style="color:#838383; margin-top:10px;">'+props.nombre+'</center></b>': '')
    +(props? '<br><b><center style="color:#838383">'+props.web+'</center></b>': '');
    +(props? '<br><img src="'+props.pic+'"style="width:40px;height:40px;">': '');
    this._div.innerHTML += '<br /><img src="link.png" style="background:rgba(254,198,41,0.8); margin-left:20px; margin-right:15px; margin-top:0px">';
};
info.addTo(map);

谁能帮我举一些关于这个动作的例子?

标签: javascripthtmljsonleaflet

解决方案


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

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

然后将该元素插入到您希望的容器元素中:

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

推荐阅读