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
user188962
4 Answers 4
Shouldn't this:
onclick='imageShow(z);'
be something like this:
onclick='imageShow(' + z + ');'
answered Dec 18, 2009 at 16:15
dcp
55.7k24 gold badges149 silver badges169 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
James
112k32 gold badges165 silver badges177 bronze badges
1 Comment
Andy E
Not sure, but +1 from me for suggesting using the DOM. It's much more efficient than invoking the HTML parser.
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
Patrick
15.7k1 gold badge42 silver badges39 bronze badges
Comments
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
Ryan
6,86613 gold badges52 silver badges68 bronze badges
Comments
lang-js
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 :)