2011-09-29 80 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元素。我现在有图像源,可以根据需要使用。