2016-10-11 35 views
0

我能夠通過一個XML飼料用下面的代碼jQuery的 - 獲取從解析的XML飼料(內容:編碼)第一圖像

$($xml).find('item').each(function(i, e) { ... } 

對於在這個循環中的每個項目進行搜索,我能夠訪問我的內容:通過下面的代碼,並查看結果編碼的元素...

$mcontent = $(this).find('encoded').text(); 
    console.log('source: ' + $mcontent.match(/<img[^>]*>/g)); 

...它包含這樣的逗號分隔的多個圖片...

<p><img src="...">, <img src="...">, <img src="..."></p> 

我怎樣才能得到第一個圖像元素,並存儲比$ mImage變量?

謝謝!

更新:

當我嘗試做以下...

$mcontent = $(this).find('encoded').text(); 
    $mcontent = $mcontent.match(/<img[^>]*>/g).split(',')[0]; 
    console.log('source: ' + $mcontent); 

瀏覽器告訴我...

Uncaught TypeError: $mcontent.match(...).split is not a function 

..和我不噸知道爲什麼...

+1

「你的圖像,字符串,在這裏」.split(',')[0]會給你第一個圖像作爲一個字符串。 –

+0

我上面還有一個問題,試圖實現這一點...我也忘了我原來的問題的一個元素... – blackhawk

+0

感謝axel提醒分裂 – blackhawk

回答

2

如果您的文字是:

<p><img src="...">, <img src="...">, <img src="..."></p> 

你可以使用:

var str = '<p><img src="...">, <img src="...">, <img src="..."></p>'; 
var firstImg = $($.parseHTML(str)[0]).find('img:first'); 

Uncaught TypeError: $mcontent.match(...).split is not a function

這是因爲「$ mcontent.match(/]>/G)」 *返回IMG的數組,這是不夠的,你得到的第一ELE:

的片段:

var str = '<p><img src="...">, <img src="...">, <img src="..."></p>'; 
 
var firstImg = $($.parseHTML(str)[0]).find('img:first'); 
 

 
console.log(firstImg[0].outerHTML); 
 

 

 

 
var t = str.match(/<img[^>]*>/g)[0]; 
 

 
console.log(t);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

也謝謝你的錯誤教育! – blackhawk