2011-09-29 81 views
1

我有一個XML文檔(從進料),我是來自提取值內標籤:找到文本字符串

$(feed_data).find("item").each(function() { 
    if(count < 3) { 
    //Pull attributes out of the current item. $(this) is the current item. 
     var title = $(this).find("title").text(); 
     var link = $(this).find("link").text(); 
     var description = $(this).find("description").text(); 

現在裏面的「描述」我需要得到img元素,但是這正在造成一些問題。 「描述」是一個常規的字符串元素,看起來我不能對此調用「.find()」方法,那麼我該怎麼做?

我已經打過電話.find()

var img = $(this).find("description").find("img"); 

但它是一個沒有去。 img被包裹在一個跨度中,但我無法達到這個要求。有什麼建議麼?我寧願避免使用子串和正則表達式解決方案,但我很茫然。

我也試着打開「描述」字符串轉換爲XML對象,像這樣:

var parser = new DOMParser(); 
var desc = parser.parseFromString(test,'text/xml'); 

$(desc).find("img").each(function() { 
    alert("something here"); 
}); 

但是,這並不工作。它似乎會,但我得到一個「文件沒有很好形成」的錯誤。

+2

請發佈您的HTML代碼 – Flatlin3

+0

至少請考慮張貼您正在使用的字符串。否則,我們只是在猜測如何提供幫助。 –

回答

3

嘗試封閉描述標籤的內容一個虛擬的div,它似乎對我更好,並允許jQuery的.find()按預期工作。

例如

$(feed_data).find("item").each(function() { 
    if(count < 3) { 
     //Pull attributes out of the current item. $(this) is the current item. 
     var title = $(this).find("title").text(); 
     var link = $(this).find("link").text(); 
     var description = '<div>' + $(this).find("description").text() + '</div>'; 
     var image = $(description).find('img'); 
+0

謝謝,這與我最終的解決方案類似,我相信這也會起作用。 – mac

+0

如果有人感興趣,我添加了我的解決方案作爲答案... – mac

1

也許你應該嘗試的說明文字轉換爲HTML標記,然後嘗試通過jQuery遍歷它

$('<div/>').html($(this).find("description").text()).find('img') 

:未測試

+0

+1類似於我的方法,這是最終工作的事情。 – GregL

3

嗨,感謝您的及時回覆。我給GregL打了個勾號,因爲我確信他的解決方案會起作用,因爲原理與我最終的原理相同。我的解決辦法是這樣的:

$(feed_data).find("item").each(function() { 
     if(count < 3) { 
      //Pull attributes out of the current item. $(this) is the current item. 
      var title = $(this).find("title").text(); 
      var link = $(this).find("link").text(); 
      var description = $(this).find("description").text(); 

      var thumbnail = ""; 
      var temp_container = $("<div></div>"); 
      temp_container.html(description); 
      thumbnail = temp_container.find("img:first").attr("src"); 

所以包裹串在一個div,然後使用「查找()」中獲得第一img元素。我現在有圖像源,可以根據需要使用。