0

I have a for loop statement that doesn't loop, here's my code:

$(document).ready(function(){
    for(var i=1;i<=30;i++){
        $('img[alt="sample'+i+'"]').click(function(){
            var changeImage = $('img[alt="sample'+i+'"]').attr('src');
            var changeText = $('img[alt="sample'+i+'"]').attr('alt');
            $('img[alt="main image"]').attr('src', changeImage);
            $('h4#imageTitleHead').text(changeText);
        });
    }
});

the i won't loop and when I check the source code the code is still the same.. like this $('img[alt="sample'+i+'"]') it didn't change to number and did not loop at all.. Please help.. Thank you in advance

Kevin Steve Maningo
  • 254
  • 2
  • 7
  • 16

4 Answers4

1

Why do a loop if you can do this:

First add any class to images which alt is sample[NUMBER] (e.g. loopImages):

<img src="image.png" alt="sample1" class="loopImages">

Now, the code:

$(document).ready(function(){
    $('img.loopImages').click(function(){
        var current = $(this);
        var changeImage = current.attr('src');
        var changeText = current.attr('alt');

        $('img[alt="main image"]').attr('src', changeImage);
        $('h4#imageTitleHead').text(changeText);
    });
});
Gabriel Santos
  • 4,934
  • 2
  • 43
  • 74
1

It's a hassle between the i from the loop and the callback function. There is only one i variable provided, that will be 31 after the last iteration of the loop. But jQuery provides a handy way to access the clicked object as the context object (aka this).

$(document).ready(function() {
  for (var i = 1; i <= 30; i++){
    $('img[alt="sample'+i+'"]').click(function() {
      var clickedObject = $(this); // wrap it in a jquery
      var changeImage = clickedObject.attr('src');
      var changeText = clickedObject.attr('alt');
      $('img[alt="main image"]').attr('src', changeImage);
      $('h4#imageTitleHead').text(changeText);
    });
  }
});

That should do the trick ;)

Tharabas
  • 3,402
  • 1
  • 30
  • 29
0

The loop itself is fine... http://jsfiddle.net/

Let's see what else is wrong...

Wait, nevermind, editting

0

This could probably be solved with a fairly simple selector.

Here's what it would look like:

$('img[alt*="sample"]')...

You could also write the function once outside of the for loop instead of re-declaring it every time the loop runs. ex.:

function bindAllImages(image){
    // same code in here
}

$('img[alt*="sample"]').bind('click', bindAllImages(image);


Also here's a JSFiddle illustrating the effect: http://jsfiddle.net/JYCLA/1/

Vita Pluvia
  • 470
  • 1
  • 4
  • 10