Reputation: 10052
so, I have an array of 15 links, and I want to pass them as img src into my html elements. My elements are all of class. card, and I figured I'd write a loop instead of hard coding it (I have to do this 45 times with different links).
so it looks like this
var picks1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
for(x=0;x<picks1.length;x++) {
$(".card:eq(x)").src = "picks1[x]";
}
is there a way to do it like this? I figure this isn't working because of the quotation marks at .card:eq(x). (there are 45 picks arrays and their .length changes from 1-15). Is there another way to do this?
This is a part of a bigger webpage, can post source if needed, basically what it does it read a log file that another program makes, then makes links to images on a third party website from it and puts them in arrays.
Upvotes: 0
Views: 79
Reputation: 1477
Lets say you have a pickArray which has 45 arrays with length 1-15.You can write like this
var i=0, length = pickArray.length, j=0, arrLen=0, arr;
for(;i<length;i++){
arr = pickArray[i];
arrLen = arr.length;
for(j=0;j<arrLen;j++) {
$(".card:eq("+j+")").src = arr[j];
}
}
Upvotes: 1
Reputation: 388396
Although all the above answers are right, I think caching the value of $('.card')
will be better
var picks1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
$(".card").slice(0, picks1.length).attr('src', function (i) {
return picks1[i]
})
Note: The .slice(0, picks1.length)
is not required if the length of $(".card")
and picks1
will be same
Upvotes: 2
Reputation: 4275
Your are setting value of picks1[x] as string , try to remove quotes. Use the code below
var picks1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
for(x=0;x<picks1.length;x++) {
$(".card").eq(x).src = picks1[x];
}
Or use it with attr() function
$(".card").eq(x).attr('src',picks1[x]);
Hope this helps you
Upvotes: 0
Reputation: 8193
var picks1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
var cards = $(".card");
for (x = 0; x < picks1.length; x++) {
cards.eq(x).attr('src', picks1[x]);
}
Upvotes: 0
Reputation: 7878
You have the use the +
-operator to insert a variable into your selector-string:
var picks1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
for(x=0;x<picks1.length;x++) {
$(".card:eq(" + x + ")").src = picks1[x];
// OR
$(".card").eq(x).attr('src', picks1[x]);
}
Upvotes: 0