即使逻辑看起来很简单,为什么单击时我的图像也不会改变?

时间:2019-04-06 14:50:56

标签: javascript debugging

我试图在单击当前图像时显示新图像。问题是,单击img-1时,它会跳到img-3。但是,如果我删除了第二个if(),它将正确地转到下一个图像(img-2)。

这是怎么回事,我该如何解决?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="index.css">
    <title>Title</title>
</head>
<body>
<img id="the-image" onclick="clickedImage()" src="https://www.folkdeal.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/f/d/fd-ea10150-1.jpg" alt="image down"/>

<script type="text/javascript">
    let theImage = document.getElementById('the-image');

    let index = {
        "img-1" : "https://www.folkdeal.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/f/d/fd-ea10150-1.jpg",
        "img-2" : "http://image.en.yibada.com/data/images/full/66771/the-legend-of-zelda-japanese-hepburn-zeruda-no-densetsu-is-a-high-fantasy-action-adventure-video-game-series-created-by-japanese-game-designers-shigeru-miyamoto-and-takashi-tezuka.png",
        "img-3" : "https://www.geekisus.com/wp-content/uploads/2018/08/01_1575-11-400x400.jpg"
    };

    let clickedImage = () => {
        if(theImage.src === index["img-1"]) {
            theImage.src = index["img-2"];
        }

        if(theImage.src === index["img-2"]) {
            theImage.src = index["img-3"];
        }
    }
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

这样做的时候

 theImage.src = index["img-2"]

这将是真的

 if(theImage.src === index["img-2"])

然后

 theImage.src = index["img-3"];

将被执行,有效地跳过第二张图像。您可能想将第二个if更改为else if