0

I have a basic for loop to create a gallery of thumbnail images:

//code to query spreadsheet...data returned as 'rows'
for (var i = 0; i<rows.length; i++){
im = rows[i][0];
n = rows[i][1];
d = rows[i][2];
c = rows[i][3];  
$('#frame').append('<div class = box><img height = 290 src = ' + im + '>');
    }

For each image there is additional information (in other columns of the spread sheet) - this is also returned as 'rows' as per the above.

Next, there is a click function to display a larger image:

$('#frame').on('click', 'img', function() {
   var s = this.src.replace(/.jpg/, '');
   $('#show').append('<img src = ' + s + 'L.jpg><div id = details><strong>' + n + '</strong><br>' + d + '<br><span class = status>' + c +'</span></div>');
});

The aim of the last bit is to display the additional information from the same row as the clicked image - and obviously it won't work as written. How do I pass the value of [i] for the clicked image to the click function to get the additional data from the same row[i] as the clicked image?

Thanks.

sideroxylon
  • 4,338
  • 1
  • 22
  • 40
  • 1
    possible duplicate of [Assign click handlers in for loop](http://stackoverflow.com/questions/4091765/assign-click-handlers-in-for-loop) – Pointy Nov 15 '13 at 23:41

2 Answers2

1

This code may work try this

for(var i = 0; i<rows.length; i++){
im = rows[i][0];
$('#frame').append('<div class = "box"> <img height =290 src = "'+ im +
'" onclick="clickImg('+i+')" >');
}
function clickImg(i){
im = rows[i][0];
n  = rows[i][1];
d  = rows[i][2];
c  = rows[i][3]; 
var s = im.replace(/.jpg/, '');
$('#show').append('<img src = "' + s + 'L.jpg" /> <div id = details><strong>' + n 
+ '</strong> <br>'+ d +'<br> <span class = "status"> ' + c +' </span> </div>');
}
SHIN
  • 386
  • 2
  • 13
0

Try this:

var im;
 for (var i = 0; i<rows.length; i++){
 im = rows[i][0]; 
 $('#frame').append('<div class = box><img id = ' + i + ' height = 290 src = ' + im + '>');
 }
 $('#frame').on('click', 'img', function() {
  var i = this.id;
  n = rows[i][1];
  d = rows[i][2];
  c = rows[i][3];
  var s = im.replace(/.jpg/, '');
  $('#show').append('<img src = "' + s + 'L.jpg" /> <div id = details><strong>' + n  + '</strong> <br>'+ d +'<br> <span class = "status"> ' + c +' </span> </div>');
sideroxylon
  • 4,338
  • 1
  • 22
  • 40