tags:

views:

73

answers:

4

I have this function, and I want to pass a variable (z) to the OnClick event of an image.

I have this:

for (z=1; z<img_src.length; z++){
    path_th_img= 'ad_images/'+category+'/'+'thumbs/'+img_src[z];
    document.getElementById("thumb_pic_div").innerHTML += "<img src='"+path_th_img+"' class='shadow2' style='margin:7px;' onclick='imageShow(z);'>";
      }

img_src.lengt is in this case 4... So no matter which of the three images I click, the nr 4 gets passed on... ideas?

Thanks

+4  A: 

Shouldn't this:

onclick='imageShow(z);'

be something like this:

onclick='imageShow(' + z + ');'
dcp
A: 

Try changing this line...

document.getElementById("thumb_pic_div").innerHTML += "<img src='"+path_th_img+"' class='shadow2' style='margin:7px;' onclick='imageShow(z);'>";

To this...

document.getElementById("thumb_pic_div").innerHTML += "<img src='"+path_th_img+"' class='shadow2' style='margin:7px;' onclick='imageShow("+z+");'>";
Ryan
+1  A: 

you have to pass the value of z in your string

for (z=1; z<img_src.length; z++) {
    path_th_img= 'ad_images/'+category+'/'+'thumbs/'+img_src[z];
    document.getElementById("thumb_pic_div").innerHTML += 
    "<img src='"+path_th_img+"' class='shadow2' style='margin:7px;' onclick='imageShow("+z+");'>";
}
Patrick
+2  A: 

Use the DOM, properly.

for (var z = 1, l = img_src.length; z < l; ++z) {

    var new_img = document.createElement('img');

    new_img.src = 'ad_images/' + category+'/' + 'thumbs/' + img_src[z];
    new_img.onclick = (function(z){
        return function() {
            imageShow(z);
        };
    })(z);
    new_img.style.margin = '7px';

    document.getElementById("thumb_pic_div").appendChild(new_img);

}
J-P
Care to explain the downvote?
J-P
Not sure, but +1 from me for suggesting using the DOM. It's much more efficient than invoking the HTML parser.
Andy E
+1 for nice readable DOM use.
Tegeril
+1 for DOM use. =D
Jeff Rupert