Javascript:改变img src onclick只能工作一次

Ale*_*lex 2 javascript

这很简单,我不知道为什么我遇到麻烦.我试图模仿两张图像之间的翻转卡,所以当点击时,它只会改变为另一张图像.我的if/else语句有问题,因为每次单击图像时,它都不会进入else部分.在HTML页面的源代码中,图像的src正在被更改,但每次都传递if语句.

(function() {

    // attaches event handler to image
    window.onload = function() {

        var image1 = document.getElementById("image1");
        image1.onclick = changeImage;
    };

    // changes image when clicked to flip from image to text and text to image
    function changeImage() {
        if (document.getElementById("image1").src = "img/top.png") {
            document.getElementById("image1").src = "img/toptext.png";
            //window.alert('hi');
        }
        else {
            window.alert('it passed');
            document.getElementById("image1").src="img/top.png";
        }
    }
})();
Run Code Online (Sandbox Code Playgroud)

Dee*_*eep 8

如果条件检查,使用==或===进行比较.

using =将赋值,并且始终为true,因为指定的字符串不是空字符串.

 function changeImage() {
        if (document.getElementById("image1").src == "img/top.png") {
            document.getElementById("image1").src = "img/toptext.png";
            //window.alert('hi');
        }
        else {
            window.alert('it passed');
            document.getElementById("image1").src="img/top.png";
        }
    }
Run Code Online (Sandbox Code Playgroud)