Dynamically replace img src attribute with jQuery

前端 未结 3 2148
清歌不尽
清歌不尽 2020-12-01 20:41

I am trying to replace the img source of a given source using jQuery. For example, when the image src is smith.gif, replace to johnson.gif. If williams.gif replace to brown.

相关标签:
3条回答
  • 2020-12-01 21:18

    In my case, I replaced the src taq using:

       $('#gmap_canvas').attr('src', newSrc);

    0 讨论(0)
  • 2020-12-01 21:19

    You need to check out the attr method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src with the string specified in the 2nd parameter.

    http://api.jquery.com/attr/

    A better way to approach replacing a series of images source would be to loop through each and check it's source.

    Example:

    $('img').each(function () {
      var curSrc = $(this).attr('src');
      if ( curSrc === 'http://example.com/smith.gif' ) {
          $(this).attr('src', 'http://example.com/johnson.gif');
      }
      if ( curSrc === 'http://example.com/williams.gif' ) {
          $(this).attr('src', 'http://example.com/brown.gif');
      }
    });
    
    0 讨论(0)
  • 2020-12-01 21:29

    This is what you wanna do:

    var oldSrc = 'http://example.com/smith.gif';
    var newSrc = 'http://example.com/johnson.gif';
    $('img[src="' + oldSrc + '"]').attr('src', newSrc);
    
    0 讨论(0)
提交回复
热议问题