user188962
user188962

Reputation:

quick javascript function help

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

Upvotes: 0

Views: 112

Answers (4)

James
James

Reputation: 111920

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);

}

Upvotes: 3

Patrick
Patrick

Reputation: 15717

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+");'>";
}

Upvotes: 0

Ryan
Ryan

Reputation: 6866

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+");'>";

Upvotes: 0

dcp
dcp

Reputation: 55449

Shouldn't this:

onclick='imageShow(z);'

be something like this:

onclick='imageShow(' + z + ');'

Upvotes: 5

Related Questions