gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:48:45 25 4
gpt4 key购买 nike

我正在使用 Ajax 调用通过 JQuery 将一些模板数据发布到我的 HTML View 。

但是,当我将数组提供给以下函数时,它仅打印出 HTML/ View 中数组中的一项。

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 正确返回了数组,但它没有打印所有项目,仅打印第一个项目。我还检查过,.each 循环的次数与数组中的项目数一样多,所以这不是问题。我缺少什么吗?

最佳答案

这是因为你正在循环覆盖内容

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);
}
});

关于javascript - 将 .html 与 JQuery 一起使用不会将数组中的所有项目发布到 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26878927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com