简体   繁体   中英

How to get one image to change to the image i click on using javascript

Hi I'm trying to create a gallery using JavaScript. I want to have a row of small images at the bottom and when you click on one it will display that image in a bigger window above. and that window currently contains and image.

New to JavaScript so not 100% sure what I'm doing. here is what I was trying to use but wasn't working. Any tips would be great thanks.:

<script>
function changeimage(val)
{
    var x = val.getAttribute("src");
    var y = getElementById("Display");
    var z = y.getAttribute("src");
    z.setAttribute("src","x");
}
</script>


<img class="mid_one" src="Images/home3.jpg" alt="home1" width="186px" height="186px" onclick="changeimage(this)"/>

Thanks in advance.

<img name="Display" id="Display" src="Images/home2.jpg" width="450" height="450" alt="Displayed Image"/>

edit: added display

Try this

function changeimage(val)
{
    var x = val.getAttribute("src");
    var y = getElementById("Display");
    y.setAttribute("src",x);
}

According to your logic var z = y.getAttribute("src"); is a string and not an Element .. In the next line you seem to set the attribute to the string ..

You should set the attribute on the element ( y ), you can't set an attribute on an attribute value ( z ).

Also, you should use the variable x to get the source from the other image, not the string "x" .

var x = val.getAttribute("src");
var y = document.getElementById("Display");
y.setAttribute("src", x);

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