2011-09-22 77 views
0

所以我有一個在變量entry.content返回這樣的數據集:如何通過jQuery抓住從HTML圖像標記

<p style="float:right;margin:0 0 10px 15px;width:240px"> <img src="http://citysportsblog.com/wp-content/uploads/2011/09/RagnarNE.jpg" width="240"> </p><p>Have you heard of the epic adventure that is the</p> 

如何將我剛剛從這個搶IMG SRC網址通過jquery?

回答

2
假設你只有一個圖像: var sourceUrl = $('img')。attr('src');
var sourceUrl = $(entry.content).find('img').attr('src'); 
+0

但看到上面的數據正在作爲純文本發送。不像html – raeq

0

你應該給你的形象的標識和使用id選擇器(你知道它只是元素你得到的方式)。您可以運行在純文本(不添加到DOM)查詢代碼如下:

string plainText = '<p style="float:right;margin:0 0 10px 15px;width:240px"> <img id="theImg" src="http://citysportsblog.com/wp-content/uploads/2011/09/RagnarNE.jpg" width="240"> </p><p>Have you heard of the epic adventure that is the</p>' 

var url = $(plainText).find('#theImg').attr('src'); 

或者,如果你不能改變它,它只是在字符串中的一個圖像多數民衆贊成:

var url = $(plainText).find('img').attr('src'); 
+0

正如提問者所說的那樣,你的jQuery代碼行可行;然而,在'#theImg'上使用'find'將不起作用,因爲它只遍歷_descendants_。 – Dennis

0

如果你沒有任何其他圖像的大小相同:

$('img[width="240"]').attr('src'); 
0

如果是我,我只是正則表達式替換來從變量來源:

entry.content = entry.content.replace("/src=\"(.+?)\"/i", "\1");

(雖然你不想使用。+;我只是懶得找到可能的URL字符)。如果你不知道entry.content會以這樣的形式,那麼我將它添加到DOM在一個隱藏的DIV,並從那裏來源:

var hiddenDiv = $(document.body).add("div"); 
hiddenDiv.css("display", "none"); 
hiddenDiv.html(entry.content); 
entry.content = hiddenDiv.find("img")[0].src; 

誠然,這是一個更爲危險的方法,因爲它讓你開放給XSS,但如果你相信源,你可以做到。

+0

雖然,如果Shawn的方法(上面)不將它添加到DOM,那麼它會更安全。 –