Toggle images on click using jQuery

2019-02-19 05:57发布

问题:

I have two images which I need to toggle on clicking on the image.

    <img id='arrowRotate' src='images/prof_arrow1.png' data-swap='images/prof_arrow.png' 
data-src='images/prof_arrow1.png' />

When the user click the image the src should get the value of data-swap and when you click again the src should change to data-src. This should keep happening just like a toggle. Any help appreciated.

$("#arrowRotate").click(function() {
    var swapImage = $("#arrowGrey").attr("data-swap");
    $("#arrowGrey").attr({
        'src': swapImage,
        id: 'arrowOrange'
    });
});  

This is where I have got so far.

回答1:

Based on my understanding from your question, Hope this is the one you expect,

$("#arrowRotate").click(function() { 
      var _this = $(this);
      var current = _this.attr("src");
      var swap = _this.attr("data-swap");     
     _this.attr('src', swap).attr("data-swap",current);   
});  

DEMO Fiddle



回答2:

Try This:

$("#arrowRotate").click(function(){
if($(this).attr('src')==$(this).attr('data-src'))
  {
    var a = $(this).attr('data-swap');
    $(this).attr('src',a);
  }     
else
  {
    var b = $(this).attr('data-src');
    $(this).attr('src',b);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id='arrowRotate' src='http://www.gettyimages.in/CMS/StaticContent/1391099215267_hero2.jpg' data-swap='http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg' data-src='http://www.gettyimages.in/CMS/StaticContent/1391099215267_hero2.jpg'>



回答3:

This might help. I think this is the simplest way of swapping between images:

<img id="arrowRotate" src="images/img1.png" data-swap="images/img2.png" data-src="images/img1.png" onclick="swapImage()" />

function swapImage(){
    var swapImage = $('#arrowRotate').attr('data-swap'),
        currentImage = $('#arrowRotate').attr('src');

    $('#arrowRotate').attr({
        'src': swapImage,
        'data-swap': currentImage
    });
};


回答4:

If I understand you right you can do it like this:

HTML

<img id='arrowRotate' src='images/prof_arrow1.png' data-swap='images/prof_arrow.png' data-src='images/prof_arrow1.png' data-swapped="false"/>

Javascript

$("#arrowRotate").click(function() {

    var swapped = $(this).attr("data-swapped");
    var init = 'false';

    if(swapped === 'false'){
        var swapImage = $(this).attr("data-swap");
        init = true;
    }else{
        var swapImage = $(this).attr("data-src");
    }

    $(this).attr({
        'src': swapImage,
        'id': 'arrowOrange',
        'data-swapped': init
    });

});