我想遍历JSON对象提供的所有帖子,并从每个帖子中提取第一张图片。这是 the Tumblr API Documentation
目前我有这段代码,只扫出第一篇文章的所有内容。我希望从所有帖子中吐出第一张图片。
$.ajax({
url: "http://api.tumblr.com/v2/blog/sjtest1.tumblr.com/posts?api_key={mykey}",
dataType: 'jsonp',
success: function(results){
console.log(results);
var postBody = results.response.posts[0].body;
$(".x").html(postBody);
}
});
这是Tumblr的JSON对象的示例文本:
{
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"blog": { ... },
"posts": [
{
"blog_name": "citriccomics",
"id": 3507845453,
"post_url": "http:\/\/citriccomics.tumblr.com\/post\/3507845453",
"type": "text",
"date": "2011-02-25 20:27:00 GMT",
"timestamp": 1298665620,
"state": "published",
"format": "html",
"reblog_key": "b0baQtsl",
"tags": [
"tumblrize",
"milky dog",
"mini comic"
],
"note_count": 14,
"title": "Milky Dog",
"body": "<p><img src=\"http:\/\/media.tumblr.com\
/tumblr_lh6x8d7LBB1qa6gy3.jpg\"\/><a href=\"http:\/\
/citriccomics.com\/blog\/?p=487\" target=\"_blank\">TO READ
THE REST CLICK HERE<\/a><br\/>\n\nMilky Dog was inspired by
something <a href=\"http:\/\/gunadie.com\/naomi\"
target=\"_blank\">Naomi Gee<\/a> wrote on twitter, I really
liked the hash tag <a href=\"http:\/\/twitter.com\/
search?q=%23MILKYDOG\" target=\"_blank\">#milkydog<\/a>
and quickly came up with a little comic about it. You can
(and should) follow Naomi on twitter <a href=\"http:\/\
/twitter.com\/ngun\" target=\"_blank\">@ngun<\/a> I'm on
twitter as well <a href=\"http:\/\/twitter.com\
/weflewairplanes\"target=\"_blank\">@weflewairplanes<\/a>
<\/p>\n\nAlso, if you’re a Reddit user (or even if
you're not) I submitted this there, if you could up vote
it I'd be super grateful just <a href=\"http:\/\
/tinyurl.com\/5wj3tqz\" target=\"_blank\">CLICK HERE<\/a>"
},
...
],
"total_posts": 3
}
}
如您所见,body
中的图片包含<p>
个标签。
有谁知道如何帮助拉动图像?
答案 0 :(得分:2)
考虑到你已经在使用jQuery,如何:
$(results.response.posts[0].body).find('img').first();
这可能不是最佳选择,但应该这样做。
如果你想为多个帖子做这件事:
var img = [];
$.each(results.response.posts, function (ix,el){
img.push($(el.body).find('img').first());
})