Replace img path jquery

2020-04-19 07:57发布

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

replace example.com/thumbs

with example.com/images

I have tried this but it doesn't seem to work.

 $("img").attr("src").replace("thumbs", "images");

6条回答
倾城 Initia
2楼-- · 2020-04-19 08:33

Step 1: script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
Step 2:

    $(document).ready(function(){
         $('img').each(function() {
               $(this).attr('src', $(this).attr('src').replace('thumbs', 'images')); 
               console.log('Latest image link ' + $(this).attr('src'));
           });
      });
查看更多
地球回转人心会变
3楼-- · 2020-04-19 08:37
var oldSrc = 'http://example.com/smith.gif';
var newSrc = 'http://example.com/johnson.gif';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);

This is what you wanna do:

查看更多
家丑人穷心不美
4楼-- · 2020-04-19 08:39

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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://img.pranavc.in/100?t=thumbs" alt="#" />
<img src="http://img.pranavc.in/100?t=thumbs1" alt="#" />
<img src="http://img.pranavc.in/100?t=thumbs2" alt="#" />
<img src="http://img.pranavc.in/100?t=thumbs3" alt="#" />
<img src="http://img.pranavc.in/100?t=thumbs4" alt="#" />
<img src="http://img.pranavc.in/100?t=thumbs5" alt="#" />
<img src="http://img.pranavc.in/100?t=thumbs6" alt="#" />

查看更多
闹够了就滚
5楼-- · 2020-04-19 08:40

 
 var newPath = $("img").attr("src").replace("thumbs", "images");
  $("img").attr("src",newPath);

查看更多
forever°为你锁心
6楼-- · 2020-04-19 08:42

This gets the value, but doesn't set it back to the attribute:

$("img").attr("src").replace("thumbs", "images");

That requires another step, something like:

var newSrc = $("img").attr("src").replace("thumbs", "images");
$("img").attr("src", newSrc);

Or, if you want a single line:

$("img").attr("src", $("img").attr("src").replace("thumbs", "images"));
查看更多
神经病院院长
7楼-- · 2020-04-19 08:51

Look at this one, you wasn't setting src for an image.

$(function() {
      $('img').each(function() {
          $(this).attr('src', $(this).attr('src').replace('thumbs', 'imagessss')); console.log('New src: ' + $(this).attr('src'));
          });
      });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="/images/thumbs.png" />

查看更多
登录 后发表回答