2010-01-24 47 views
0

我有一個頁面,我屏幕抓取,刮的頁面使用相對路徑爲他們的圖像,當我加載我的網頁時,我的網站的URL被插入到src attr。我需要找到一些方法,用遠程站點的URL替換我的url,以便引用它的圖像和其他項目在我的頁面上正確顯示。jQuery如何替換src url

我用刮的腳本是:

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

我已經加入了最後一行與.replace希望清理問題,但到目前爲止,這是行不通的。我需要保留文件路徑,所以當我用目標url替換我的url時,其餘的src attr需要留在那裏。例如,當頁面打開時,我看到表格和所有文本都很好,但圖像無法加載,因爲它們不駐留在我的服務器上。所以,我需要從這個更新SRC ATTR:

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

這樣:

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

任何有識之士將不勝感激。

+1

過得好跨域HTML – SLaks 2010-01-24 15:18:48

回答

3

replace調用返回一個包含替換項的新字符串。 您的代碼會創建一個新字符串,表示my_site.com而不是weather.com,但對字符串不做任何處理。

你需要編寫如下:?

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

我認爲這是相當'函數(指數錯字,舊的)' – Gumbo 2010-01-24 15:28:18

+0

@Gumbo:你是對的,謝謝。 – SLaks 2010-01-24 15:29:28

+0

似乎沒有改變網址,表仍然加載,但它仍然沒有更新路徑。 – Jason 2010-01-25 11:57:55

1

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