JQuery question about passing through an array

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 to use the jQuery function each()as follows:

$('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?

+3
source share
5 answers

You need to pass parameters for each callback.

$(gridArray).each(function (i, val) {
  // i is the index in this loop.
  // val is the value at gridArray[i] in this loop.
});
+2
source

Check out the jQuery Documentation for jQuery.each. Function Signature:

jQuery.each( collection, callback(indexInArray, valueOfElement) )

I am not 100% sure what you are trying to accomplish, so it’s hard to give a concrete example, but that should make you.

0
source

, <li>:

$('li.node').each(function(i) {
  var rndTile = gridArray[i];
  $(this).css({ 'background-image': 'url(images/'+rndTile+'.jpg' });
});
0
$('li.node').each(function(index) {
    var rndTile = gridArray[index % gridArray.length];
    $(this).css({ 'background-image': 'url(images/' + rndTile + '.jpg' });
});
0

bad , for in , jQuerys .each(). .

Use for..inor .each()if you don't know how many items you need to deal with (which in turn actually means using only for objects ).

Use a regular loop forto iterate over an array.

for(var n = 0, len = gridArray.length; n < len; n++){
}
0
source

Source: https://habr.com/ru/post/1756446/


All Articles