jQuery each()将所有项目从feed添加到div

时间:2016-04-15 13:58:13

标签: javascript jquery html rss

我正在尝试从rss Feed中获取项目,并将每个项目放在不同的div中。这是我的代码:

$.ajax({
  url      : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent('FEED URL'),
  dataType : 'json',
  success  : function (data) {
    if (data.responseData.feed && data.responseData.feed.entries) {
      $.each(data.responseData.feed.entries, function (i, e) {
        $('<div class="inner"></div>').appendTo('#feed');   
        $(".inner").attr('data-role','collapsible');
        $(".inner").append("<h2>"+e.title+"</h2>");
        $(".inner").append("<p>"+e.content+"</p>");
        $(".inner").collapsible();
        //console.log("------------------------");
        //console.log("title      : " + e.title);
        //console.log("author     : " + e.author);
        //console.log("description: " + e.content);
      });
    }
  }
});

问题是,在创建下一个项目之前,它还会将Feed中的每个项目添加到div中。输出是这样的:

---可折叠Div与第1项目 ------第2项
------第3项
------第4项
---可折叠的Div与第2项
------第3项
------第4项
---可折叠Div与第3项
------第4项

3 个答案:

答案 0 :(得分:1)

$(".inner")搜索当前位于文档中的类inner所有元素,因此$(".inner").append("some HTML")会将其附加到所有他们。

如果您只想使用该迭代的那个,请将其保存到变量中,然后使用该变量:

var inner = $('<div class="inner"></div>').appendTo('#feed');   
inner.attr('data-role','collapsible');
// ...and so on...

答案 1 :(得分:-1)

如果返回此类的所有元素(包括刚刚添加的元素),则问题是选择器.inner。将$(".inner")更改为$(".inner:last-child")

答案 2 :(得分:-2)

我建议你看一下你正在做的回报的控制台输出。如果您有Chrome或Firefox,请打开控制台。在您的代码中,您应该输入:

case

我的猜测是,回报的结构并不完全符合你的想法。

谢谢, -Kyle

相关问题