There is a loop (in my gallery script) that result me something like this :
<div class="gallery">
<a href="uploads/rep2.png">
<img src="uploads/rep2-150x110.png" class="thumbnail">
</a>
</div>
<div class="gallery">
<a href="uploads/rep1.png">
<img src="uploads/rep1-150x110.png" class="thumbnail">
</a>
</div>
<div class="gallery">
<a href="uploads/rep2.png">
<img src="uploads/rep2-150x110.png" class="thumbnail">
</a>
</div>
I want add specific attr (that is “href” of each link) to each image in this loop. Must be:
<div class="gallery">
<a href="uploads/rep2.png">
<img data-img="uploads/rep2.png" src="uploads/rep2-150x110.png" class="thumbnail">
</a>
</div>
<div class="gallery">
<a href="uploads/rep1.png">
<img data-img="uploads/rep1.png" src="uploads/rep1-150x110.png" class="thumbnail">
</a>
</div>
<div class="gallery">
<a href="uploads/rep2.png">
<img data-img="uploads/rep2.png" src="uploads/rep2-150x110.png" class="thumbnail">
</a>
</div>
I wrote this code:
$('.thumbnail').each(function() {
var $this = $('.gallery a'),
href = $this.data('href');
$('.thumbnail').attr('data-img', href);
});
But not work.Thanks for any help.
Close but you need to use
thisin each callback.First take all the a tags in gallery, find their href, apply that to the img tag which is a child.
The key trick here is that
each()sets the this variable to the element iterated over for each callback.