简体   繁体   中英

Why won't the image in my HTML change with my JavaScript function?

Simply put, I have three images, and I'd like to cycle through them when I click on the image. In other words, I want the img src to change to the next specified image when it is clicked on. However, this doesn't happen. Keep in mind all of the images I have are in the same folder as my html code, and each image loads just fine by themselves, they just won't cycle through.

Here is my code:

<!Doctype html>
<html>
<head>
</head>
<body>

<p>Hello world</p>

<img onclick="changePic()" id="pika" src="pichu.gif" alt="pichu">

<script>
    function changePic() {
    var pika = document.getElementById("pika").src;

    if(pika == "pichu.gif") {
        pika = "pikachu.gif";
    } else if (pika == "pikachu.gif") {
        pika = "raichu.gif";
    } else  {
        pika = "pichu.gif";
    }
}
</script>

</body>
</html>

the source property of your image is not a reference property. so changing the variable pika doesn't effect the src property of the pika element.

if you set the pika variable to the element itself, then check and set the SRC values in your if else statements you should be good.

var pika = document.getElementById("pika");
if (pika.src == "pichu.gif") {
   pika.src = "Pikachu.gif"
}  etc...

Edit:

Forgot to point out also that your SRC property may not be just the file name but could also be the patch to the file name depending on how you have your HTML and folder structure setup.

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