3

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 caption. 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 = '';
});
mtro
  • 31
  • 1
  • 2
  • 1
    why do you need to clear the caption variable? – b01 Jul 29 '11 at 13:24
  • 1
    Here is what worked: jQuery('.node-type-article .imagefield-imagelink img').each(function() { jQuery(this).after( jQuery('
    ') .text( jQuery(this).attr('title')) ); });
    – mtro Jul 29 '11 at 13:28
  • I'm liking JQuery although a lot going on, on one line it feels very elegant – Paul C Jul 29 '11 at 13:36

4 Answers4

4

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.

FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
0

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.

Mrchief
  • 75,126
  • 20
  • 142
  • 189
0

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','');
});
Darcy
  • 5,228
  • 12
  • 53
  • 79
0

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.

Luke Duddridge
  • 4,285
  • 35
  • 50