Reputation: 10713
I have an array like this:
var gridArray = [ 1,2,0,1,2,3,2,1,2,3,4,4,3,2,2,2,0 ]
And I would like a jQuery each()
function like this:
$('li.node').each(function() {
loop through the array
var rndTile = the current array digit
$(this).css({ 'background-image': 'url(images/'+arrayDigit+'.jpg' });
});
How could I implement this?
Upvotes: 3
Views: 476
Reputation: 236162
It is in general a bad idea to loop over an array with for in
or even worse, jQuerys .each()
. Looping like that means lots of unnecesarry overhead.
Only use for..in
or .each()
if you don't know how many items you have to deal with (that in turn actually means only use it for objects).
Use a normal for
loop to iterate over an array.
for(var n = 0, len = gridArray.length; n < len; n++){
}
Upvotes: 0
Reputation: 1039438
$('li.node').each(function(index) {
var rndTile = gridArray[index % gridArray.length];
$(this).css({ 'background-image': 'url(images/' + rndTile + '.jpg' });
});
Upvotes: 0
Reputation: 338406
Assuming every array member correspondends to an <li>
:
$('li.node').each(function(i) {
var rndTile = gridArray[i];
$(this).css({ 'background-image': 'url(images/'+rndTile+'.jpg' });
});
Upvotes: 0
Reputation: 7875
Have a look at the jQuery Documentation for jQuery.each. The function signature is:
jQuery.each( collection, callback(indexInArray, valueOfElement) )
I'm not 100% sure what you're trying to accomplish, so it's hard to give a concrete example, but this should get you going.
Upvotes: 0
Reputation: 48028
You need to pass parameters to your each callback.
$(gridArray).each(function (i, val) {
// i is the index in this loop.
// val is the value at gridArray[i] in this loop.
});
Upvotes: 2