0

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

4

2 回答 2

1

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')" />
于 2013-08-06T07:43:00.837 回答
1
  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.

于 2013-08-06T07:58:25.937 回答