I have an array of objects (data)
data[0].image = image1.jpg;
data[0].name = "some name";
data[1].image = image2.jpg;
data[1].name = "some name";
data[2].image = image3.jpg;
data[2].name = "some name";
data[3].image = image4.jpg;
data[3].name = "some name";
I also have a group of tags nested in a ul.
<ul class='swapme'>
<li><img class="swapme" src="a.jpg" /></li>
<li><img class="swapme" src="b.jpg" /></li>
<li><img class="swapme" src="c.jpg" /></li>
<li><img class="swapme" src="d.jpg" /></li>
</ul>
I know I can grab the img tags with
$('ul.swapme').children('img.swapme')
I know I can swap out each images src attribute with
$('img.swapme').attr('src', data[0].image)
My question is, what is the right way to swap out the src attribute with the corresponding data object. ie, a.jpg becomes image1.jpg. . . ect. . .
If I use loops it looks ugly and clumsy, can anyone provide a better way / the right way to do this ?
You can use an
$.each()loop and utilize theindex:Note that I changed
$('ul.swapme').children('img.swapme')to$('ul.swapme').find('img.swapme')as the image tags are not direct descendants of the unordered list tag.Here is a jsfiddle of this solution: http://jsfiddle.net/jasper/Bycse/