$.each 只是遍历我数组中的最后一项......为什么会这样?

$.each is only iterating through the last item in my array...Why is this happening?

我正在尝试从我的数据库中获取一个数组,然后针对该数组中的特定项目,将其放入某个 HTML 中并让它在浏览器中呈现。在我的代码中,alert(v.displayName) 将遍历我集合中的所有 'displayName'。但是,当我将它放入 html 元素时,它只打印出数组中的最后一项。如果我输入 return false $('.commentsForTheWin') 那么它只会打印出数组中的第一项。

$(function() {
    $('.commentsInit').click(function() {
        var uniCommID = $(this).attr("value");
        $.ajax({
            type: "GET",
            url: "/api/comments"
        }).success(function(users) {
            $.each(users, function(i, v) {
                alert(v.displayName);
                var b = '<div class="red">' +
                    '<div>' +
                    '<span>' +
                    i + " : " + v.username +
                    '</span>' +
                    '<span>' +
                    " hello" +
                    '</span>' +
                    '<span>' +
                    "45 pts" +
                    '</span>' +
                    '</div>' +
                    '</div>';
                $('.commentsForTheWin').html(b);
            });
            $('.hideOnLoad:contains(' + uniCommID + ')').toggle("slow");
        })
    })
});

我猜它不喜欢我把它放进去。html?但是 .text 也不会改变它。感谢任何帮助!

改用append()

 $('.commentsForTheWin').append(b);

.html() 覆盖选择器元素中的所有内容。

在循环中创建 html 并在获得全部时将它们放入其中的更好方法:

var b='';
$.each(users, function(i, v) {
  b += '<div class="red">' +
    '<div>' +
    '<span>' +
    i + " : " + v.username +
    '</span>' +
    '<span>' +
    " hello" +
    '</span>' +
    '<span>' +
    "45 pts" +
    '</span>' +
    '</div>' +
    '</div>';
});
$('.commentsForTheWin').html(b);

问题出现是因为 .html() 覆盖了现有内容,因此您得到的是上次迭代添加的内容。

您需要使用 .append() instead of .html() and empty() 删除现有内容。

//Remove the content before iteration
$('.commentsForTheWin').empty();

$.each(users, function (i, v) {
    ...
    //append new content
    $('.commentsForTheWin').append(b);
});

另一种方法是创建一个完整的 HTML 字符串,然后使用 .html()

var htmlContent = '';
$.each(users, function (i, v) {
    ...
    //append new content
    htmlContent += b;

});
$('.commentsForTheWin').html(b);

使用 .append() 而不是 .html(),因为 .html() 在每次迭代中都会覆盖 commentsForTheWin 元素中的现有内容。