Changing the image source using jQuery

前端 未结 16 2309
天命终不由人
天命终不由人 2020-11-22 01:24

My DOM looks like this:

16条回答
  •  天涯浪人
    2020-11-22 02:22

    You can use jQuery's attr() function. For example, if your img tag has an id attribute of 'my_image', you would do this:

    
    

    Then you can change the src of your image with jQuery like this:

    $("#my_image").attr("src","second.jpg");
    

    To attach this to a click event, you could write:

    $('#my_image').on({
        'click': function(){
            $('#my_image').attr('src','second.jpg');
        }
    });
    

    To rotate the image, you could do this:

    $('img').on({
        'click': function() {
             var src = ($(this).attr('src') === 'img1_on.jpg')
                ? 'img2_on.jpg'
                : 'img1_on.jpg';
             $(this).attr('src', src);
        }
    });
    

提交回复
热议问题