[英]I am trying to get my image to display from this for loop from the array object
I am trying to get the links in the array objects to display when the loop goes through but they appear as broken links.我试图让数组对象中的链接在循环通过时显示,但它们显示为断开的链接。 broken link code
断开的链接代码
<p id= "tracks"> </p>
<div id = "images"> </div>
<script>
let songs = [
{
title: "Getting Away with It (All Messed Up)",
artist: "James",
album: "Pleased to Meet You",
year: 2001,
art: "https://upload.wikimedia.org/wikipedia/en/2/2a/JamesPleasedToMeetYou.jpg"
},
{
title: "Renaissance Affair",
artist: "Hooverphonic",
album: "Blue Wonder Power Milk",
year: 1998,
art: "https://upload.wikimedia.org/wikipedia/en/1/17/Hooverphonic-Blue_Wonder_Power_Milk.jpg"
},
{
title: "White Nights",
artist: "Oh Land",
album: "Oh Land",
year: 2011,
art: "https://upload.wikimedia.org/wikipedia/en/6/68/Oh_Land_%28album%29.png"
}
]
// Javascript Code here
element_p = document.getElementById("tracks")
//alert (element_p.innerHTML);
let text = "";
for (let data of songs) {
let new_paragraph= document.createElement ('p');
new_paragraph.innerHTML = 'Title: '+ data.title + " <br> Album: "+ data.album+ ' <br> Artist: ' + data.artist + "<br> Year: "+ data.year
element_p.appendChild(new_paragraph)
}
element_div = document.getElementById ("images")
let image = "";
for (let photo of songs){
let img_node = document.createElement ('IMG');
img_node.setAttribute('src', "data.art");
document.getElementById("images").appendChild (img_node);
}
What am I doing wrong?我究竟做错了什么? I tried two different ways and this way is the only way at least the broken links show up.
我尝试了两种不同的方法,这种方法是至少显示损坏链接的唯一方法。 Any help or insight is appreciated.
任何帮助或见解表示赞赏。
Instead of 'data.art' you have to pass in the url from each photo you are passing in by using photo.art您必须使用 photo.art 从您传入的每张照片中传入 url 而不是“data.art”
You should use img_node.setAttribute('src', photo.art)
.您应该使用
img_node.setAttribute('src', photo.art)
。 like below example:像下面的例子:
...
for (let photo of songs){
let img_node = document.createElement ('img');
img_node.setAttribute('src', photo.art);
document.getElementById("images").appendChild(img_node);
}
You have data.art
in quotes so its treated as a string instead of an object.您将
data.art
放在引号中,因此将其视为字符串而不是 object。 Also, your for loop is declaring photo
so you should change data.art
to photo.art
.此外,您的 for 循环正在声明
photo
,因此您应该将data.art
更改为photo.art
。 Like this:像这样:
for (let photo of songs){
let img_node = document.createElement ('IMG');
img_node.setAttribute('src', photo.art);
document.getElementById("images").appendChild (img_node);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.