ab01fazl ab01fazl - 4 months ago 11
jQuery Question

i cannot set my background images based on an array

i want to set the background images of my divs based on an array
html

<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>


i want to set each background image based on an array

var image_src = new Array ("1.jpg","2.jpg","3.jpg","4.jpg","5.jpg");
for (i = 0; i < 5; i++){
$("div div div").css("background-image","url(" + image_src[i] + ")");
}


each source to each div

Answer

Your selector is wrong (the third div). Consider using each jQuery function like this:

var image_src = [ "1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg" ];

$("div.container div").each(function(i) {
    $(this).css("background-image","url(" + image_src[i] + ")")
});
Comments