Using jQuery .each() to append title attribute below multiple images.
How can I use .each() to get a var, use it, clear it and then start fresh with the next loop of .each()?
I've got a varying number of images with 'title' attribute. I want to take the title attribute and append it to a new div after each image, creating a capti开发者_运维百科on. Using the following code on a page with 2 images, however, I get both of their titles under each image.
How can I run .each() so that it does it's work on the first image, erases it's var, then does it's work on the second image?
jQuery(".node-type-article .imagefield-imagelink img").each( function() {
var caption = jQuery(this).attr('title');
jQuery(this).after('<div class="caption"></div>');
jQuery('.caption').append(caption);
caption = '';
});
This is the offending line. It's matching both divs:
jQuery('.caption').append(caption);
Do this:
jQuery(".node-type-article .imagefield-imagelink img").each(function() {
var caption = jQuery(this).attr('title');
jQuery(this).after('<div class="caption">' + caption + '</div>');
});
Also, you don't need to clear the caption var. It's local to each invocation of the function.
Every iteration will start a fresh scope. You don't need to erase
the var caption
as it'll automatically go out of scope after the iteration.
Your problem is here:
caption = '';
This will work:
jQuery(".node-type-article .imagefield-imagelink img").each( function() {
var caption = jQuery(this).attr('title');
jQuery(this).after('<div class="caption"></div>');
jQuery('.caption').append(caption);
this.title = ''; //or the jQuery way --> $(this).attr('title','');
});
Your culprit is: jQuery('.caption').append(caption);
this will find all objects with the class of caption and append the caption text to it.
What you area probably seeing is one caption with one title and then one with 2.
The fix is to add a next
statement, so instead of:
jQuery('.caption').append(caption);
you do:
$(this).next('.caption').html(caption);
// $ and jQuery are the same thing btw
EDIT
Sorry forgot to add, you dont need to clear you caption variable.
Because you have defined your variable within the each
function, it will create a new variable each time.
精彩评论