jQuery如何替换src url

我有一个屏幕被抓取的页面,被抓取的页面使用了他们的图像的相对路径,当我加载我的页面时,我的网站的url被插入src attr。 我需要找到一些用远程站点的url替换我的url的方法,以便引用它的图像和其他项目在我的页面上正确显示。

我用来刮的脚本是:

  $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"); }); }); }); 

我已经添加了最后一行.replace希望清理问题,但到目前为止它无法正常工作。 我需要保留文件路径,所以当我用目标url替换我的url时,src attr的其余部分需要保留在那里。 例如,当页面打开时,我看到表格和所有文本都很好,但图像无法加载,因为它不驻留在我的服务器上。 所以我需要从这里更新src attr:

 http://sofzh.miximages.com/jquery/sunny.jpg 

对此:

 http://sofzh.miximages.com/jquery/sunny.jpg 

任何见解将不胜感激。

replace调用返回包含替换的新字符串。 您的代码会创建一个新的字符串,表示my_site.com而不是weather.com ,但不会对字符串执行任何操作。

您需要编写以下内容:

 $(this).attr("src", function(index, old) { return old.replace('http://my_site.com', 'http://weather.com"); }); 

你有’ 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); }); }); });