javascript:图片不会改变

时间:2014-06-10 11:04:09

标签: javascript html

我很确定逻辑很好,但由于其他原因,当我点击图像时,它不会改变。所有图像都在同一个目录中,我可以加载lightOn.png图像,但不能更改它。

<!DOCTYPE html>
<html>
    <body>
        <script>
            function changeImage() {
                if (document.getElementById("myimg").src == "lightOn.png") {
                    document.getElementById("myimg").src = "lightOff.png";
                }
                else {
                    document.getElementById("myimg").src = "lightOn.png";
                }
            }
        </script>
        <img id="myimg" onclick="changeImage()" src="lightOn.png">
        <p>Turn on/off the light</p>
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

似乎存在的唯一问题是img src不正确,请确保图像路径正确。我改变了路径并且它有效http://jsfiddle.net/Y4yCb/

<body>
        <script>
            function changeImage() {
                if (document.getElementById("myimg").src == "http://www.freeimageslive.com/galleries/light/pics/light00002g.jpg") {
                    document.getElementById("myimg").src = "http://solar.calfinder.com/assets/blog/images/energy-light-off.jpg";
                }
                else {
                    document.getElementById("myimg").src = "http://www.freeimageslive.com/galleries/light/pics/light00002g.jpg";
                }
            }
        </script>
        <img id="myimg" onclick="changeImage()" src="http://www.freeimageslive.com/galleries/light/pics/light00002g.jpg">
        <p>Turn on/off the light</p>
    </body>