简体   繁体   中英

javascript change Image by clicking thumbnail

I am a newbie in javascript and tried a lot of things for hours, but nothing worked.

I will change a big imgage by clicking on a thumbnail.

Untill now I got following script. Not much really... :-(

<script type="text/javascript">
    function changeImage() {
        document.getElementById("img").src="img/upload/test1.jpg";
    }
</script>

<img id="img" name="change" src="img/upload/test.jpg">
<img src="img/thumbnail/test.jpg" alt="" id="imgClickAndChange" onclick="changeImage()">
<img src="img/thumbnail/test1.jpg" alt="" id="imgClickAndChange" onclick="changeImage()">

All big picture are under src"img/upload/xxx.jpg" and all thumbnails under src="img/thumbnail/xxx.jpg" . When I click the thumbnail, it have to change the big picture and it have to give the parameter in the javascript. Like onclick="changeImage(xxx.jpg) .

The problem is every page have other pictures. I get them from a database. So the name of the picture is like a variable. I hope you understand. It is hard for me to explain. :-(

Thanks for your help in advance.

Greets Yanick

Pass the image parameter to the function like,

function changeImage(image) {
    document.getElementById("img").src=image;
}

<img src="img/thumbnail/test.jpg" alt="" id="img" 
            onclick="changeImage('img/upload/test1.jpg')" />
  1. Keep ids unique. DOM elements "must" possess unique IDs for all practical reasons.
  2. Though you could do an inline onclick, a better way to proceed with it is something as follows.

Assuming you have the images generated from some templating library either on the client or from the server, add data attributes with the image sources and a common class to all of these elements right there and add an event listener from your Javascript bound to elements matching the class and picking up the data attribute to replace the image source.

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