我的JSON文件看起来像这样:
[
{
"destination": "Hawaii",
"description": "...etc, etc",
"images": {
"image": [
"hawaii1.jpg",
"hawaii2.jpg",
"hawaii3.jpg",
"hawaii4.jpg"
]
}
},
***more destinations continuing on***
我的图像放在一个文件夹中,但是HTML变成空白,只显示边框。这是我的Javascript代码:
function createTrip(tripData) {
let ul = document.getElementsByTagName("ul")[0];
for(let i = 0; i < tripData.length; i++){
let keys = Object.keys(tripData[i]);
let values = Object.values(tripData[i]);
**** code appending my data into a li element****
for (let j = 0; j < values.length; j++) {
let label = document.createElement("label");
let span = document.createElement("span");
let img = document.createElement("img");
label.innerHTML = `${keys[j]}:`;
span.innerHTML = `${values[j]}`;
img.innerHTML = `${tripData[i].images.image[0]}`;
li.appendChild(img);
ul.appendChild(li);
}
}
为什么我的图像没有显示?
您将innerHTML属性设置为img
,这是错误的,请尝试将图像名称放在.src属性中。
... code ...
img.src = `${tripData[i].images.image[0]}`;
... code ...
尝试
d = [
{
"destination": "Hawaii",
"description": "...etc, etc",
"images": {
"image": [
"hawaii1.jpg",
"hawaii2.jpg",
"hawaii3.jpg",
"hawaii4.jpg"
]
}
},
//...
]
s = '';
d.map(trip => {
trip.images.image.map(img => {
s += `
<li>
<label>${trip.destination}</label>
<img src=${img}/>
<span>${trip.description}</span>
</li>`;
})
})
trips.innerHTML = s;
<ul id="trips"></ul>