【问题标题】:Extracting image from <description> RSS feed with AngularJS使用 AngularJS 从 <description> RSS 提要中提取图像
【发布时间】:2016-01-28 16:46:06
【问题描述】:

我正在尝试学习 AngularJS,同时构建一个简单的 RSS 提要。我设法发出一个 JSON 请求并检索我解析的所有数据、标题、链接、描述和所有 RSS。我像这样提取图像:

angular.forEach(feed.entries, function(value){
        value.myImage = $(value.content).find('img').eq(0).attr('src');
        console.log('image' + value.myImage);
}

但是,有些提要具有不同的结构,而是将图像放置在 &lt;content&gt; &lt;/content&gt; 中,例如 this,图像放置在 &lt;description&gt; &lt;/description&gt; 中,例如 this one,我正在尝试以这种方式获取它:

angular.forEach(feed.entries, function(value){
    value.myImage = $(value.description).find('img').eq(0).attr('src');
    console.log('no image' + " " + value.myImage);
});

但我得到的只是未定义的,所以我无法显示此提要中的图像。我尝试了不同的方法,但我真的迷路了,我不确定我在这里做错了什么。

我已经在谷歌上搜索并尝试了好几个星期。任何帮助都非常感谢!

谢谢:)


这是我得到的 JSON 对象。

Object {feedUrl: "https://www.behance.net/rss", title: "Behance Featured Projects", link: "http://www.behance.net", author: "", description: "The latest projects featured on the Behance"…}
$$hashKey: "027"
author: ""
description: "The latest projects featured on the Behance"
entries: Array[10]
0: Object
$$hashKey: "029"
author: ""
categories: Array[0]
content: "<img src="https://mir-s3-cdn-cf.behance.net/projects/404/2e322a33145177.Y3JvcCw4NzYsNjg0LDAsNzc.jpg" style="float:left;margin-right:15px"><br> Various Illustrations by Patryk Hardziej / 2015"
contentSnippet: " Various Illustrations by Patryk Hardziej / 2015"
link: "https://www.behance.net/gallery/33145177/Various-Illustrations-2015"
publishedDate: "Thu, 28 Jan 2016 08:00:02 -0800"
sImage: undefined
title: "Various Illustrations 2015"

【问题讨论】:

  • 在你的例子中,你没有影响 $(value.description).find('img').eq(0).attr('src');到 value.sImage 变量。也许就是这样:)
  • value.sImage = $(value.description).find('img').eq(0).attr('src');
  • @YoannProt 谢谢,只是没有正确复制那行,但事实并非如此!我修改了代码:D
  • 你能添加一个你收到的 JSON 的例子吗?
  • @YoannProt 我在帖子上添加了它。

标签: javascript angularjs rss


【解决方案1】:

好的,我想我找到了:)

你从查询中得到的 HTML 看起来像

<img src="..."> Some text <br/> Some text ...

find 方法仅适用于查找子节点。在这种情况下,img 不是 value.content 的孩子,所以它什么也不返回。

你可以的

angular.forEach(feed.entries, function(value){
  // force creation of a root node -> find method should works for all cases
  var content = '<div>'+value.content+'</div>';
  value.myImage = $(content).find('img').eq(0).attr('src');
  console.log('image' + value.myImage);
}

【讨论】:

  • 是的,伙计!你明白了:D 非常感谢,非常感谢你的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多