如何从Javascript数组中提取图像并将其放入HTML?

时间:2019-02-09 14:04:52

标签: javascript html css arrays json

我有以下包含图像及其元数据的代码数组。 `

const images = [
    {
        "src": "Image1.jpeg",
        "title": "A two tone wall",
        "tags": ["wall", "two tone"]

    },
    {
    "src": "image2.jpeg", 
    "title": "Cute doggy", 
    "tags": ["dog", "walkies"]
},
{
    "src": "image3.jpeg",
    "title": "Natural splendor", 
    "tags": ["natural", "mountain"]
},
{
    "src": "image4.jpeg",
    "title": "Man looking at phone", 
    "tags": ["man", "phone"]
},
{
    "src": "image5.jpeg",
    "title": "Wavey wave",
    "tags": ["water", "wave"]
},
{
    "src": "image6.jpeg",
    "title": "Mountain range",
        "tags": ["mountain", "grass"]
    }

]`

,并希望将它们放入带有附加元数据的2 x 3网格中。目前,我尝试使用JQUERY将它们解析为2个不同的行作为对象,但仅显示文本。

有人可以帮助我吗?我对Java语言还很陌生,但了解一些原理。

1 个答案:

答案 0 :(得分:1)

喜欢吗?

const cont = document.querySelector(".cont");

const images = [
    {
        "src": "https://picsum.photos/300/200",
        "title": "A two tone wall",
        "tags": ["wall", "two tone"]

    },
    {
    "src": "https://picsum.photos/320/200", 
    "title": "Cute doggy", 
    "tags": ["dog", "walkies"]
},
{
    "src": "https://picsum.photos/330/200",
    "title": "Natural splendor", 
    "tags": ["natural", "mountain"]
},
{
    "src": "https://picsum.photos/300/210",
    "title": "Man looking at phone", 
    "tags": ["man", "phone"]
},
{
    "src": "https://picsum.photos/300/220",
    "title": "Wavey wave",
    "tags": ["water", "wave"]
},
{
    "src": "https://picsum.photos/300/230",
    "title": "Mountain range",
     "tags": ["mountain", "grass"]
    }

];

images.forEach(function(par){
  cont.innerHTML += `<img src="${par.src}" alt="${par.title}">`;
});
.cont {
  display:grid;
  grid-template-columns:1fr 1fr 1fr;
}

img {
  width: 200px;
  height: 200px;
}
<div class="cont"></div>