简体   繁体   中英

javascript load image to div onclick

I want to display image user click from image link in a for loop to a div.

my for loop is as follows.

<a href='' name=my_image[i]

onclick='disp_image('link_image_url')'id=my_image[i]  class='popup-open'><img src=my_image[i] width='80' height='65'></a>;

and my javascript function

<script language=\"javascript\">


function disp_image(url){

document.getElementById('image').innerHTML ="<img src=url width='100' height='105'>";

;}

</script>


</script>

However it is not being load in my div content

<div id="image"></div>

can someone has an idea how can i display selected image in a div content dynamically

Use this:

var _leng = my_image.length
  , td = "<td><a href='#url#' onclick='displaying(/image#url#)' id='/image#url#'><img src='#url#' width='80' height='65' /></a></td></tr><tr>"
  , i; 

for (i=0; i < _leng; i++) {
  str += td.replace(/#url#/g, my_image[i])
}

Check this example: http://jsfiddle.net/hMfRG/

You have mismatched quotes so the string isn't being generated properly, or at all... you probably have errors in the console.

str += "<td><a href='" + my_image[i] + " onclick='displaying()' id='/image" + my_image[i] + "'><img src='" + my_image[i] + "' width='80' height='65' /></a></td></tr><tr>";

You can't use these special quotes '' or , only use these single or double quotes ' or " .

Example:

document.getElementById('image')

You have displaying() in the loop but below, its called displayImage() . Also, the function expects an argument which you're not supplying in the call.

Look at the syntax highlighting of your post. You can clearly see that your quotes are all over the place. For instance, you have src='"+url+'" , which is wrong. You also have "smart quotes" in places. Fix the quotes and it should stop throwing syntax errors.

But most importantly, your onclick function calls displaying() , whereas the function is called displayImage and takes an argument.

I've done it this way:

<div id="result" style="width:450px;height:296px;">
<img name="main" src="/images/image.jpg" alt="">
</div>

function change_pic(img_name,img_src) 
{
  document[img_name].src=img_src;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM