JavaScript:更改IMG SRC ONCLICK仅工作一次



这太简单了,我不确定为什么我会遇到麻烦。我正在尝试模仿两个图像之间的翻转卡,因此单击时,它只会更改为另一个图像。我的if/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";
        }
    }
})();

use ==或===在情况检查中进行比较。

使用=将分配值,并且始终为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";
        }
    }

您应该使用== for comparaison

if (document.getElementById("image1").src = "img/top.png") {

更改为

if (document.getElementById("image1").src == "img/top.png") {

最新更新