I am trying to display images into thumbnails for my image gallery by using for...in
loop but it is only able to display one image. I am still a beginner in javascript, so my understanding of for loops is still not good. Where did I go wrong?
sample array:
["http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
"http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png"]
for...in
loop:
for(var thumb in thumbnails) {
$('.thumbnail img').attr({"src":[thumbnails[thumb]]});
}
Actually, your loop is perfectly fine. You do iterate over all the URLs in your array, but for each URL you set it as src
for the same thumbnail img
, effectively overwriting it each time.
It is hard to help you fix it, because I don't know your exact layout and requirements, but you effectively either need to create a set of img
s for thumbnails (as opposed to just one img
, which seems to be the case now), and set their src
s in order, or create brand new img
each time and append it to some parent container, like so:
for(var thumb in thumbnails) {
$(<some container>).append($('<img>').attr({"src":[thumbnails[thumb]]}));
}