如果长度 % 3 == 1 或 == 2,则添加类

Addclass if length % 3 == 1 or == 2

我有几个网格,每行 3 个项目,如果最后一行只有 1 个项目,我需要将 addClass 添加到最后一个项目;如果有 2 个,我需要将 addClass 添加到 'before last' 项目最后一行的项目。

见下文:

$('.row').each(function(){
  if ($('.item').length % 3 == 2){
    $(this).find('.item').last().addClass('col-lg-offset-4');
  } else if ($('.item').length % 3 == 1){
    $(this).find('.item').last().prev().addClass('col-lg-offset-2');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

<div class="row">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

你能帮我解决这个问题吗?我做错了什么? 提前谢谢你...

试试这个

$('.row').each(function(){
  if ($(this).find('.item').length % 3 == 2){
    $(this).find('.item').last().addClass('col-lg-offset-4');
  } else if ($(this).find('.item').length % 3 == 1){
    $(this).find('.item').last().prev().addClass('col-lg-offset-2');
  }
});

DEMO HERE

试试这样的东西,我还没有测试过,但应该给你一个提示。

$('.row').each(function(){
    // Calculate Last Item Count
    var lastItem = $(this).find('.item').last();
    var lastItemCount = lastItem.length
    // I need to addClass to the last item if in the last row there is only 1 item
    if (lastItemCount == 1) {
        lastItem.addClass('col-lg-offset-4');
    }
    // or addClass to the 'before last' item if there are 2 items in the last row.
    if (lastItemCount == 2) {
        lastItem.prev().addClass('col-lg-offset-2');
    }
});

您的代码运行良好,唯一的问题是在迭代每个 .row div 时您正在寻找

$('.item').length

实际上会在整个页面中查找所有带有 class .item 的 div,而不仅仅是您所在的现有行,解决方案是在该特定行中查找项目 div 通过使用

$(this).find('.item').length

所以你的代码应该是

$('.row').each(function(){
  var itemsCount = $(this).find('.item').length;
  if (itemsCount % 3 == 2){
     $(this).find('.item').last().addClass('col-lg-offset-4');
  } else if (itemsCount % 3 == 1){
     $(this).find('.item').last().prev().addClass('col-lg-offset-2');
  }
});