假設JSON數據是正確的結構:
let jsonData = [
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"},
{src: "#", width: "165px", height: "95px"}
];
您可以在幾個不同的方式做到這一點,在下面的代碼中,我們首先創建一個容器div
,然後遍歷JSON數組創建一個新的圖像元素,然後將其添加到容器。最後,這個div追加的body元素:
let jsonData = [
{src: "http://via.placeholder.com/165x95", width: "165px", height: "95px"},
{src: "http://via.placeholder.com/165x95", width: "165px", height: "95px"},
{src: "http://via.placeholder.com/165x95", width: "165px", height: "95px"},
{src: "http://via.placeholder.com/165x95", width: "165px", height: "95px"},
{src: "http://via.placeholder.com/165x95", width: "165px", height: "95px"},
{src: "http://via.placeholder.com/165x95", width: "165px", height: "95px"},
{src: "http://via.placeholder.com/165x95", width: "165px", height: "95px"}
];
const container = document.createElement('div');
const bodyElement = document.querySelector('body');
const images = jsonData.map(image => {
let imageEl = document.createElement('img');
imageEl.setAttribute('src', image.src);
imageEl.setAttribute('height', image.height);
imageEl.setAttribute('width', image.width);
return imageEl;
});
for (let image of images) {
container.appendChild(image);
}
bodyElement.appendChild(container);
https://jsbin.com/qokilubeze/edit?html,js,output
這可以進一步簡化:
const container = document.createElement('div');
const bodyElement = document.querySelector('body');
for (let i = 0; i < jsonData.length; i++) {
let imageEl = document.createElement('img');
imageEl.setAttribute('src', jsonData[i].src);
imageEl.setAttribute('height', jsonData[i].height);
imageEl.setAttribute('width', jsonData[i].width);
container.appendChild(imageEl);
}
bodyElement.appendChild(container);
或者:
const container = document.createElement('div');
const bodyElement = document.querySelector('body');
jsonData.map(image => {
let imageEl = document.createElement('img');
imageEl.setAttribute('src', image.src);
imageEl.setAttribute('height', image.height);
imageEl.setAttribute('width', image.width);
container.appendChild(imageEl);
});
bodyElement.appendChild(container);
這不是一個有效的JSON。如果你有一個詞典的話,那麼你會錯過大括號和逗號。 –