简体   繁体   中英

Toggle src-attribute on image

Is there a way to toggle the src attribute of an image between two values when an anchor is clicked?

Like this:

$('a#some-anchor').click(function() {
// code here that toggles between two image src's e.g. "images/some-image1.jpg" and "images/some-image2.jpg"
});
$("img").bind("click", function() {
  var src = ($(this).attr("src") === "img1_on.jpg")
                ? "img2_on.jpg" 
                : "img1_on.jpg";
  $(this).attr("src", src);
});

Taken from here:

Changing the image source using jQuery

Using internal data() function could work:

$('a#some-anchor').click(function() {
  var img = $(this);
  if ( img.data('active') ) {
    img.attr('src', 'images/some-image1.jpg');
    img.data('active', false);
  } else {
    img.attr('src', 'images/some-image2.jpg');
    img.data('active', true);
  }
});

Don't know where you image are but:

$('a#some-anchor').click(function() {
    var img = $('selector');

    if (img.attr('src').match(/image1/)) {
        img.attr('src', 'images/some-image2.jpg');
    } else {
        img.attr('src', 'images/some-image1.jpg');
    }
});
$('a#some-anchor').click(function() {
    var img = $('#yourIMG');

    var img1 = "images/some-image1.jpg";
    var img2 = "images/some-image2.jpg";

    img.attr('src', img.attr('src') == img1 ? img2 : img1);
});

Checkout this snippet:

 var plus = 'https://d30y9cdsu7xlg0.cloudfront.net/png/5805-200.png'; var minus = 'https://d30y9cdsu7xlg0.cloudfront.net/png/5802-200.png'; $('#magic-toggle').click(function() { if ($('.fun-img').attr('src') === plus) { $('.fun-img').attr('src', minus); } else { $('.fun-img').attr('src', plus) } }) 
 .fun-img { width: 80px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img src="https://d30y9cdsu7xlg0.cloudfront.net/png/5805-200.png" class="fun-img" id="magic-toggle"> 

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