jQuery how to replace src url

2019-08-21 11:40发布

I have a page that I screen scraped, the scraped page used a relative path for their images and when I load my page, the url of my site is being inserted on the src attr. I need to find some way of replacing my url with the url of the remote site in order for the images and other items that reference it to show up properly on my page.

The script I use to scrape is:

<script src="path_to_jquery.js"></script>
<script>
$document.ready(function() {
 $("#weather").load("http://weather.com" table:nth-child(3)", function() {
  $(this).find("img").each(function() {
   $(this).attr("src").replace('http://my_site.com', 'http://weather.com");
  });
 });
});

I have added the last line with .replace hoping to clean up the problem but so far it is not working. I need to keep the file path so when I replace my url with the target url the rest of the src attr needs to stay there. For example when the page is opened I see the table and all the text fine, but the images fail to load since the do not reside on my server. So I need to update the src attr from this:

http://my_site.com/images/sunny.jpg

to this:

http://weather.com/images/sunny.jpg

Any insight would be appreciated.

2条回答
老娘就宠你
2楼-- · 2019-08-21 12:10

You have typo in 'http://weather.com"

$document.ready(function() {
 $("#weather").load("http://weather.com" table:nth-child(3)", function() {
  $(this).find("img").each(function() {
    var old_site= $(this).attr("src");
    var new_site= old_site.replace("http://my_site.com", "http://weather.com");
    $(this).attr("src",new_site);
  });
 });
});
查看更多
3楼-- · 2019-08-21 12:18

The replace call returns a new string containing the replacements. Your code creates a new string that says my_site.com instead of weather.com, but doesn't do anything with the string.

You need to write the following:

$(this).attr("src", function(index, old) {
    return old.replace('http://my_site.com', 'http://weather.com");
});
查看更多
登录 后发表回答