Replace img path jquery

前端 未结 6 942
后悔当初
后悔当初 2021-01-26 18:48

I am trying to replace an img path in jquery (injecting into a remote page)

replace example.com/thumbs

with ex

6条回答
  •  梦毁少年i
    2021-01-26 19:14

    You need to update the attribute with the returned value for that you can use a callback function as the second argument in attr() method where the second argument holds the current attribute value.

    $('img').attr('src', function(i, src){ 
       return src.replace('thumbs', 'images'); 
    });
    

    The above method will iterate over the img tags if there are multiple img elements so you can avoid using each() method for iterating.

    setTimeout(function() {
      $('img').attr('src', function(i, src) {
        return src.replace('thumbs', 'images');
      });
    }, 2000);
    
    #
    #
    #
    #
    #
    #
    #

提交回复
热议问题