此代码处理来自 RSS 提要的响应。它组织并附加到内容。如果嵌入了视频,则将其与其余内容分开。我想主要对性能/效率进行审查,但我也愿意接受任何其他建议。那个星选择器真的让我很烦,但我不知道有更好的方法来迭代所有包含的元素。
function getFeed(url, element, callback) {
$.getJSON("https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q="+encodeURIComponent(url), function(response) {
var content = "",
$element = $(element);
for (var i = 0; i < response.responseData.feed.entries.length; i++) {
content = content + response.responseData.feed.entries[i].content; //Join all the feed entries
}
$element.find(".content").html(content).addClass($element.find("embed").length? "withVideo" : "");
$element.find("*").each(function() {
var $this = $(this);
$this.removeAttr("style width align"); //Reset all the crap that comes with the response
if ($this.is("embed")) {
$element.append("<div class='video'></div>");
$this.attr("width", 640).attr("height", 360).parent().appendTo(element + " .video");
};
});
if (typeof callback === 'function') {
callback();
};
});
}
然后这样调用:
getFeed("http://www.kent.k12.wa.us/site/RSS.aspx?PageID=3854", "#TechExpo", optionalCallback);
这是响应的样子
<div width="500" style="whatever"><p>Some text blah blah blah.</p>
<p align="right">Some more text</p>
</div>
<div><h2>Video Title</h2>
<embed src="http://..." width="360" height="202" type="application/x-shockwave-flash"></embed>
<small>Watch the 7th annual Tech Expo highlights.</small></div>