简体   繁体   English

为什么我的 HTML 中的图像不会随着我的 JavaScript 函数而改变?

[英]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.换句话说,我希望 img src 在单击时更改为下一个指定的图像。 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.请记住,我拥有的所有图像都与我的 html 代码位于同一文件夹中,并且每个图像都可以自行加载,它们只是不会循环。

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.所以改变 pika 变量不会影响 pika 元素的 src 属性。

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.如果您将 pika 变量设置为元素本身,那么检查并在您的 if else 语句中设置 SRC 值,您应该会很好。

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.还忘了指出,您的 SRC 属性可能不仅仅是文件名,还可能是文件名的补丁,具体取决于您如何设置 HTML 和文件夹结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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