I have an issue with each loop and I’m trying to learn. I have a for loop and it iterates through a set number, then what I want to do is set a caption through each images I have set up.
Jquery Code:
for(i=0; i<numImages; i++) {
var previewCaptions = $('span#tooltips'+(i+1)).text();
$("ul.selector").find('li').each(function(){
$(this).attr('title',previewCaptions);
});
}
HTML Code:
<span id="tooltips1" class="tip">Caption 1</span>
<span id="tooltips2" class="tip">Caption 2</span>
<span id="tooltips3" class="tip">Caption 3</span>
<ul>
<li><img src="src1" /></li>
<li><img src="src2" /></li>
<li><img src="src3" /></li>
</ul>
My problem is that it is only getting the last span text from the each(). How do I set up the each where it will iterate through one caption at a time instead of only getting the last one?
Since the captions and images are a 1:1, I would do the following:
This will cycle through each image (should make this selector more specific). With each cycle, the index (first image has index of 1, second has index of 2, etc) of the image is taken and the appropriate span (first image, first span; second image, second span, etc) is found, resulting in its text being added to the title attribute of the image.
You could even simplify it further:
This results in the following:
Online Demo: http://jsbin.com/odeciv/edit : http://jsbin.com/odeciv/2/edit