jQuery图像交换if-else语句不起作用

jQuery image swap if-else statement not working

本文关键字:语句 不起作用 if-else 交换 图像 jQuery      更新时间:2023-09-26

我对jQuery有问题。

我有以下代码,它在$(document).ready(function() {...})

 $("#one_div").hide();
 $('#button').click(function(){
        if (this.src == 'img/img1.png'){        
            this.src = 'img/img2.png';
        } 
        else {
            this.src = 'img/img1.png';
        }
        $("#one_div").slideToggle(800);
    });

CCD_ 2是图像的ID。one_div是分区的ID。

实际上,单击图像会切换div,但问题是图像只交换了一次,从img1切换到img2,而且从未切换回来。我做错了什么?

您忘记了第二台=

(this.src == 'img/img1.png'){   

将代码放在$(window).load(function() { ... });中,以确保在切换图像之前加载了图像。

$(document).ready(function() {
$("#one_div").hide();
});
$(window).load(function() {
    $('#button').click(function(){
        if ($(this).attr('src') == 'img/img1.png'){        
            $(this).attr('src', 'img/img2.png');
        } 
        else {
            $(this).attr('src', 'img/img1.png');
        }
        $("#one_div").slideToggle(800);
    });
});

为什么不使用类来切换图像?代码未经测试,但它应该变成这样:

$("#one_div").hide();
 $('#button').click(function(){
        this.toggleClass('active');
        if (this.hasClass('active')){     
            this.src = 'img/img2.png';
        } else {
            this.src = 'img/img1.png';
        }
        $("#one_div").slideToggle(800);
    });

试试这个:

 $('#button').click(function(){
    var el = document.getElementById('button');
    if (el.src == 'img/img1.png'){        
        el.src = 'img/img2.png';
    } 
    else {
        el.src = 'img/img1.png';
    }
    $("#one_div").slideToggle(800);
});

我认为这返回了一个JQUERY对象,而不是可以使用.src 操作的DOM对象