1

I'm dynamically loading images in a grid, which displays images with a link to some lightbox. This is the way im currently doing it:

$(".selection_thumb").each( function(i) {
    $(this).append("<a data-lightbox='image-1' href='img/folder/folder/"+(++i)+".jpg'><img src='img/folder/"+(++i)+".jpg' alt='alttext' /></a>");  
});

But it seems to be loading this:

<a data-lightbox="image-1" href="img/folder/folder/1.jpg"><img src="img/folder/2.jpg" alt="alttext" /></a>

But it needs to be:

<a data-lightbox="image-1" href="img/folder/folder/1.jpg"><img src="img/folder/1.jpg" alt="alttext" /></a>

So it is loading different numbers 1 and 2 instead of 1 and 1.

Any help is appreciated

user2099810
  • 361
  • 5
  • 15

2 Answers2

2

You need to use i++ not ++i because ++i adds diferently

++i returns the value of i after it has been incremented. i++ returns the value of i before incrementing.

Quoted from What's the difference between ++i and i++ in JavaScript

Community
  • 1
  • 1
Anton
  • 32,245
  • 5
  • 44
  • 54
1

Try,

var cache = null;

$(".selection_thumb").each( function(i) {
    cache = ++i; 
    $(this).append("<a data-lightbox='image-1' href='img/folder/folder/"+ cache +".jpg'><img src='img/folder/"+ cache  +".jpg' alt='alttext' /></a>");  
});
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130