检查jQuery.each中的最后一次迭代

ryevplcw  于 2022-11-03  发布在  jQuery
关注(0)|答案(6)|浏览(149)

我们如何检查jQuery.each()循环的最后一次迭代?我的循环正在对来自$.ajax请求的对象进行迭代。

  1. jQuery.ajax({
  2. url: "<?php echo $this->getUrl('xs4arabia/index/getFetchrOrderLogs/'); ?>",
  3. type: "GET",
  4. data: {
  5. tracking_id: tracking_id
  6. },
  7. dataType: "json",
  8. success: function(data) {
  9. jQuery.each(data, function(key, value) {
  10. console.log(value);
  11. })
  12. }
  13. });
bxpogfeg

bxpogfeg1#

虽然其他答案都是正确的,但我个人最喜欢这种方法,只需编写自己的计数器:

  1. var counter = 0;
  2. $(yourselector).each(function(index,element){
  3. counter++;
  4. if( counter == $(yourselector).length )
  5. {
  6. // Last Element
  7. }
  8. else
  9. {
  10. // Not last Element
  11. }
  12. });
展开查看全部
xuo3flqw

xuo3flqw2#

传递给each()处理函数的第一个参数是数组中当前元素的索引(尽管您当前将其命名为key)。您可以将其与数组的长度进行比较,以找出您当前的位置:

  1. $.each(data, function(index, value) {
  2. var isLastElement = index == data.length -1;
  3. if (isLastElement) {
  4. console.log('last item')
  5. }
  6. console.log(value);
  7. };

下面是使用本机forEach()方法的另一个示例:

  1. data.forEach((val, i) => {
  2. var isLastElement = index == data.length -1;
  3. if (isLastElement) {
  4. console.log('last item')
  5. }
  6. console.log(value);
  7. });
展开查看全部
hzbexzde

hzbexzde3#

每个函数的第一个参数等于索引。
因此,您可以将索引与数据的长度进行比较。
请看使用div标签的示例:
第一个
下面是另一个使用包含数组属性的对象的示例:
第一个

bxjv4tth

bxjv4tth4#

You can check the length of data and compare it with the key (note that the first key is 0)

  1. jQuery.ajax({
  2. url: "<?php echo $this->getUrl('xs4arabia/index/getFetchrOrderLogs/'); ?>",
  3. type: "GET",
  4. data: {tracking_id: tracking_id},
  5. dataType: "json",
  6. success: function (data) {
  7. var arrLength = data.length;
  8. jQuery.each(data, function (key, value) {
  9. if( key == arrLength - 1 ) {
  10. /* this is the last one */
  11. }
  12. console.log(value);
  13. },
  14. })
kxe2p93d

kxe2p93d5#

每一个都传递给你的函数键和值。2检查键(索引)和数据的长度。

  1. if (key == data.length- 1) {
  2. console.log('Last field');
  3. }
ldfqzlk8

ldfqzlk86#

对于form-group的类列表有答案。如果它是for循环的最后一次迭代,它将不执行任何操作。如果它是其他值,它将检查是否已经存在margin-bottom 3 px的引导类,并将其添加

  1. $(".form-group").each(function(index, value) {
  2. var isLastElement = index == $(this).length;
  3. if (isLastElement) {
  4. console.log($(this));
  5. } else if (!$(this).hasClass("mb-3")) {
  6. $(this).addClass("mb-3");
  7. }
  8. });

相关问题