0

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

asked Dec 18, 2009 at 16:12
1
  • Using document.getElementById(el).innerHTML += "..." in a for loop is very inefficient because you are invoking the HTML parser many times. It's better to assign the HTML to a variable and then apply the variable to the innerHTML property once after the loop has finished, thus invoking the parser only once. Just a suggestion :) Commented Dec 18, 2009 at 16:34

4 Answers 4

5

Shouldn't this:

onclick='imageShow(z);'

be something like this:

onclick='imageShow(' + z + ');'
answered Dec 18, 2009 at 16:15
Sign up to request clarification or add additional context in comments.

Comments

3

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);
}
answered Dec 18, 2009 at 16:21

1 Comment

Not sure, but +1 from me for suggesting using the DOM. It's much more efficient than invoking the HTML parser.
0

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+");'>";
}
answered Dec 18, 2009 at 16:16

Comments

0

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+");'>";
answered Dec 18, 2009 at 16:16

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.