我正在尝试使用以下JS代码显示RSS。但是,当我执行此操作时,两个RSS提要都更改为相同的内容(稍后执行),所有提要都附加到同一div。我认为rss = this引起了问题。任何解决方法?

HTML:

<div id="rss1" class="rss-widget">
        <ul></ul>
</div>
<div id="rss2" class="rss-widget">
        <ul></ul>
</div>
<div id="rss3" class="rss-widget">
        <ul></ul>
</div>


JS:

function RSSWidget(id, url) {

rss = this;
rss.FEED_URL = url;

rss.JSON = new Array();
rss.widgetHolder = $('#' + id + ' ul ');
rss.storiesLimit = 15;

rss.renderBlogItem = function (object) {
    var item = '<li class="blog-item">';
    item += '<a href="' + object.link + '">';
    item += '<div class="blog-item-title">' + object.title + '</div>';
    item += '<div class="blog-item-author">' + object.author + '</div>';
    // item += '<div class="blog-item-content">' + object.content + '</div>';
    item += '</a>'
    item += '</li>';

    rss.widgetHolder.append(item);
}

return $.ajax({
    url: 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(rss.FEED_URL),
    dataType: 'json',
    success: function (data) {
        if (data.responseData.feed && data.responseData.feed.entries) {
            $.each(data.responseData.feed.entries, function (i, e) {
                rss.JSON.push({ //add objects to the array
                    title: e.title,
                    author: e.author,
                    content: e.content || "",
                    link: e.link
                });
            });

            if (rss.storiesLimit > rss.JSON.length)
                rss.storiesLimit = rss.JSON.length;

            for (var i = 0; i < rss.storiesLimit; i++) {
                rss.renderBlogItem(rss.JSON[i]);
            }

            $('#' + id + ' li ').each(function () {
                var delay = ($(this).index() / rss.storiesLimit) + 's';
                $(this).css({
                    webkitAnimationDelay: delay,
                    mozAnimationDelay: delay,
                    animationDelay: delay
                });
            });

        }
    }
});

}

$.when(RSSWidget('rss1', "http://rss.cnn.com/rss/money_markets.rss"))
.then(function () {
    RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews")
})
.then(function () {
    RSSWidget('rss3', "http://finance.yahoo.com/rss/topfinstories")
});

最佳答案

.then(RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews"));


立即被调用。尝试在RSSWidget匿名函数中调用第二个.then()

.then(function() {
  RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews")
})


同样,RSSWidget也不会返回任何承诺。您可以在return $.ajax(/* settings */)中包含RSSWidget以从RSSWidget返回jQuery Promise对象。

10-08 01:32