Javascript: How to embed and truncate Tumblr blog posts
Using Tumblr's JSON API, I have embedded blog posts into another website. However, the blog posts are long and the idea is just to show a snippet of the most recent posts, with a link if they wish to read more.
You can see the example here: http://jsbin.com/ibede5/9 - edit at your will.
For each 开发者_Python百科post, I need to truncate and add an ellipsis ('...'). The only problem is that doing so through the JSON API is almost impossible since there are so many hidden code characters (meaning my working first post example extracts the characters using .substring(35868, 36070)
which is just insane). It doesn't work on the second post either.
So ideally I need to truncate only once the JSON API code has been transferred into standard HTML.
Also, the only way I've found to include images from the posts is by appending the post a second time and using 'display: none;
to hide the text, leaving just the image. Surely there's a better way?
Any ideas? Should I even bother using their JSON API for this?
Many thanks.
I think you need to set the post['regular-body'] to an element's innerHTML property to be able to retrieve the body as text, then do a substring on that:
elem = $('<div></div>');
elem.html(p['regular-body']);
text = elem.text();
body = text.substring(0, 128);
Now that elem
contains all of the HTML from p['regular-body']
, you can search within it. To find <img>
elements, do:
var images = $(elem).find('img');
精彩评论