简体   繁体   中英

jQuery image swap if-else statement not working

I have a problem with jQuery.

I have the following code which is inside a $(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);
    });

#button is the ID of an image. one_div is the ID of a div.

Actually, clicking on the image toggles the div, but the problem is that the image is swapped only once, from img1 to img2 , and never switched back. What I did I do wrong?

你忘了第二个=

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

Put the code inside of a $(window).load(function() { ... }); instead to be sure the images are loaded before toggling them.

$(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);
    });
});

why don't you toggle the image using a class? Code is untested, but it should become something like this:

$("#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);
    });

Try this:

 $('#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);
});

I think that this has returned a JQUERY object not a DOM object that you can manipulate using .src

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM