【问题标题】:$.each is only iterating through the last item in my array...Why is this happening?$.each 只遍历我数组中的最后一项......为什么会这样?
【发布时间】:2017-05-14 12:40:12
【问题描述】:

我正在尝试从我的数据库中获取一个数组,然后针对该数组中的特定项目,将其放入一些 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 也不会改变它。任何帮助表示赞赏!

【问题讨论】:

  • 你能给我们看一个“用户”的样本吗
  • 每次调用$.each() 时都需要追加数据,而不是简单地覆盖HTML
  • html() 将覆盖现有的详细信息。使用 append()

标签: javascript jquery arrays each


【解决方案1】:

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

您需要使用.append() 而不是.html()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);

【讨论】:

  • 他也可以使用 html() 但他必须将 b 变量初始化为一个字符串,然后使用 + 运算符连接每个 $.each 迭代,在这里写这个只是为了有一个完整的范围回复
  • 这解决了一切!谢谢!我会在 4 分钟后接受答复
【解决方案2】:

改用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);

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-18
      • 2019-11-17
      • 1970-01-01
      • 2021-09-10
      • 2020-07-30
      • 2019-10-18
      • 2021-04-09
      • 1970-01-01
      相关资源
      最近更新 更多