将.html与JQuery一起使用,不会将数组中的所有项发布到html

Using .html with JQuery not posting all items in an array to HTML

本文关键字:html 一起 JQuery 数组      更新时间:2023-09-26

我使用Ajax调用将一些模板数据发布到JQuery的HTML视图中。

但是,当我将数组馈送到下面的函数时,它只在HTML/视图中打印出数组中的一个项。

Ajax调用:

request = $.ajax({ 
              url: "/fans/follow", 
              type: "post", success:function(data){
                var results = data;
                $.each(results, function( index, value ) { 
                    var template = '<li>'
                   +'<div class="row-fluid">'
                   +'<article class="span3">'
                   +'<a href="/fans/"'+value.fan_tag+'>'
                   +'<img src="https://graph.facebook.com/'+value.fbid+'/picture" alt="" height="40" width="40">'
                   +'</a>'
                   +'</article>'
                   +'<article class="span9 userDescp">'
                   +'<span>'
                   +'<a href="/fans/"'+value.fan_tag+'>'
                   +value.first_name+' '+value.last_name
                   +'</a>'
                   +'</span>'
                   +'</article>'
                   +'</div>'
                   +'</li>';
                   $('div#new_content').find('ul').html(template);
                });
              }, 
              data: {'id': id} ,beforeSend: function(data){
                console.log(data);
              } 
            });

应该打印模板的HTML:

<div id="new_content">
    <ul></ul>
</div>

在控制台中查看,ajax正确地返回了数组,但它并没有打印所有项目,只打印第一个项目。我也检查过,每个循环的循环次数与数组中的项目数量一样多,所以这不是问题所在。我缺了什么吗?

这是因为您正在覆盖循环中的内容

request = $.ajax({
    url: "/fans/follow",
    type: "post",
    success: function (data) {
        var results = data,
            //cache a reference and emtpy the ul
            $ul = $('#new_content').find('ul').empty();
        $.each(results, function (index, value) {
            var template = '<li>' + '<div class="row-fluid">' + '<article class="span3">' + '<a href="/fans/"' + value.fan_tag + '>' + '<img src="https://graph.facebook.com/' + value.fbid + '/picture" alt="" height="40" width="40">' + '</a>' + '</article>' + '<article class="span9 userDescp">' + '<span>' + '<a href="/fans/"' + value.fan_tag + '>' + value.first_name + ' ' + value.last_name + '</a>' + '</span>' + '</article>' + '</div>' + '</li>';
            //add the template to the existing contents instead of overwriting it
            $ul.append(template);
        });
    },
    data: {
        'id': id
    },
    beforeSend: function (data) {
        console.log(data);
    }
});