JQBolo JQBolo - 1 month ago 8
Javascript Question

Jquery $.each loop dealing with array

I'm working with an array of URLs inside an object in jquery and I'm at the point where I'm super close to being finished, however I'm having a small issue.

I've bound the following loop to a click function, when the user clicks on a photo (at [location]) a bunch of corresponding photos SHOULD load below, these photos are stored in an array and I can successfully access the array inside the correct objects, but instead of inserting the URLS sequentially it inserts EVERY URL into each photo seperated by commas.

i.e instead of:

img src="[0]"
,
img src="[1]"
,
img src="[2]"
...

I am presented with:
img src="[0],[1],[2]"
...

$.each(albums[location].photos, function(index, val){
$('#'+cover_id+'').append('<div id="'+cover_id+'" class="thumbnail" style="display:inline-block; padding: 0 25px;"><img src='+albums[location].photos+' id="coverPhoto" height="320" width="320"><figcaption>'+location+'</figcaption></a></div>');
});


I'm thinking I could solve it using another loop, but that seems clunky due to using $.each.

Any help would be greatly appreciated

Answer

you have to use the parameters of the $.each

you have 2 ways, use the index or the value

 $.each(albums[location].photos, function(index, val){   $('#'+cover_id+'').append('<div id="'+cover_id+'" class="thumbnail"
 style="display:inline-block; padding: 0 25px;"><img
 src='+albums[location].photos[index]+' id="coverPhoto" height="320"
 width="320"><figcaption>'+location+'</figcaption></a></div>'); });

or

$.each(albums[location].photos, function(index, val){   $('#'+cover_id+'').append('<div id="'+cover_id+'" class="thumbnail"
style="display:inline-block; padding: 0 25px;"><img
src='+val+' id="coverPhoto" height="320"
width="320"><figcaption>'+location+'</figcaption></a></div>'); });
Comments