jQuery如何替换src url [英] jQuery how to replace src url

查看:84
本文介绍了jQuery如何替换src url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我使用的脚本是:

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



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

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



c $ c> http://weather.com/images/sunny.jpg

任何见解都会赞赏。

解决方案

替换调用会返回一个包含替换项的新字符串。
您的代码创建了一个新字符串,它表示 my_site.com ,而不是 weather.com ,但doesn'你可以编写以下代码:

 <$ c 

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


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.

解决方案

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

这篇关于jQuery如何替换src url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆