最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Changing image src onClick with jQuery - Stack Overflow

programmeradmin4浏览0评论

I am using this HTML on my site: <a href="#1" id="slick-toggle"><img src="img1.jpg"/></a>

When I click this link, I would like to change the image src to img2.jpg. And revert back to img1.jpg when clicked again & so on. Can someone explain how I do this using jQuery?

Here is my existing jQuery if this helps:

$(document).ready(function() {     
  $('#slick-toggle').click(function() {
    $('#slickbox').toggle(400);
    return false;
  });
});

Many thanks for any pointers with this :-)

I am using this HTML on my site: <a href="#1" id="slick-toggle"><img src="img1.jpg"/></a>

When I click this link, I would like to change the image src to img2.jpg. And revert back to img1.jpg when clicked again & so on. Can someone explain how I do this using jQuery?

Here is my existing jQuery if this helps:

$(document).ready(function() {     
  $('#slick-toggle').click(function() {
    $('#slickbox').toggle(400);
    return false;
  });
});

Many thanks for any pointers with this :-)

Share Improve this question asked Dec 15, 2012 at 18:11 michaelmcgurkmichaelmcgurk 6,50925 gold badges100 silver badges197 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 8
$(document).ready(function() {     
  $('#slick-toggle').click(function() {
    $('img', this).attr('src', function(i, oldSrc) {
        return oldSrc == 'img1.jpg' ? 'img2.jpg' : 'img1.jpg';
    });
    $('#slickbox').toggle(400);
    return false;
  });
});

You need to find the image inside since your click handler is on the that wraps it, like this:

$('a#slick-toggle').click(function() {
  var img = $('#share')[0], isSwap = "True";
  img.src = isSwap ? img.src.replace("_img1","_img2") : img.src.replace("_img2","_img1");
  $('.img-swap').toggleClass("on");
  $('#atBox').toggle(100);
  return false;
});

Use this function for this:

$('#mylink').toggle(
     function(){
          $(this).attr('src','img2.jpg');
     },
     function(){
          $(this).attr('src','img3.jpg');
     }
// and so on..
);

you can add more function in it...

发布评论

评论列表(0)

  1. 暂无评论