为什么我的循环只返回一个值?

时间:2022-08-31 20:37:02

Here's my html code:

这是我的HTML代码:

<div id="1">

  <div class="latest">
  </div>

  <div class="myclass">

  </div>

</div>

Here's my jquery:

这是我的jquery:

$.each(data, function(k, v) {

    var len = data.length;

    $('.myclass').each(function() {

        if ($('.myclass').length == len) {
            $('.myclass').remove();
            $('.latest').prepend('<div class="myclass">' + v.TheDatas + '</div>');
        }

    });

});

My problem here is if the v.TheDatas has many values, for example the total value of the v.TheDatas is 5 then it Only gives the first value and print it 5 times. What i want is print the all data 5 times.

我的问题在于如果v .Datas有很多值,例如v的总值.Datas是5然后它只给出第一个值并打印5次。我想要的是打印所有数据5次。

1 个解决方案

#1


Because the first match it finds, it removes all the elements with selector you run the loop for

因为它找到了第一个匹配项,所以它会删除运行循环的选择器的所有元素

$('.myclass').remove();

Instead of $('.myclass') inside each you should use $(this).

而不是每个内部的$('。myclass')你应该使用$(this)。

Something like:

$.each(data, function(k, v) {
    var len = data.length;

    $('.myclass').each(function() {
        if ($(this).length == len) {
            $(this).remove();
            $('.latest').prepend('<div class="myclass">' + v.TheDatas + '</div>');
        }
    });
});

#1


Because the first match it finds, it removes all the elements with selector you run the loop for

因为它找到了第一个匹配项,所以它会删除运行循环的选择器的所有元素

$('.myclass').remove();

Instead of $('.myclass') inside each you should use $(this).

而不是每个内部的$('。myclass')你应该使用$(this)。

Something like:

$.each(data, function(k, v) {
    var len = data.length;

    $('.myclass').each(function() {
        if ($(this).length == len) {
            $(this).remove();
            $('.latest').prepend('<div class="myclass">' + v.TheDatas + '</div>');
        }
    });
});