【问题标题】:How to add and remove class in a loop with jQuery如何使用 jQuery 在循环中添加和删除类
【发布时间】:2016-10-17 22:27:47
【问题描述】:

我有一个 3 x 3 的网格。 红色类需要添加到我的网格单元格中。它必须从cell1继续到cell 9,一旦到达cell9,它应该再次从cell1开始。在 cell2 位置,它必须检查 cell1 是否有 red 类,如果有,则将其删除并将“red”类添加到 cell2,这个过程应该永远持续下去。

$(document).ready(function () {

    // setInterval(AddRedClass(), 1000)

});

function AddRedClass() {
    var boxes = $('.box');
    var boxLength = boxes.length - 1;
    var lastChildIndex;

    for (var index = 0; index < boxLength;) {

        var currentBox = $(boxes[index]);
        var lastChildIndex = (index == 0) ? boxLength : index - 1;
        var prevBox = $(boxes[lastChildIndex]);

        if (prevBox.hasClass('red'))
            setTimeout(prevBox.removeClass('red'), 1000);

        setTimeout(currentBox.addClass('red'), 1000);
        index = (index + 1) % boxLength;
    }

}
.container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    width: 250px;
}

.box {
    width: 30%;
    border: 1px solid green;
}

.red {
    background: red!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
        <div class="box">
            c-1
        </div>
        <div class="box">
            c-2
        </div>
        <div class="box">
            c-3
        </div>
        <div class="box">
            c-4
        </div>
        <div class="box">
            c-5
        </div>
        <div class="box">
            c-6
        </div>
        <div class="box">
            c-7
        </div>
        <div class="box">
            c-8
        </div>
        <div class="box">
            c-9
        </div>
    </div>

谁能解释一下我的代码有什么问题。

谢谢

【问题讨论】:

  • 你为什么要删除然后再添加红色类?

标签: jquery css flexbox


【解决方案1】:

你不需要检查上一个单元格是否有类,我想你只需要将它添加到下一个[i] 项目。在此处查看 cmets:

//Create a var to store the index of red element
var count = -1;
function AddRedClass() {
  var boxes = $('.box');
  var boxLength = boxes.length - 1;
  //Check if the actual item isn't more than the length then add 1 otherway restart to 0
  count < boxLength ? count++ : count=0;
  //Remove the class and add it to the new target
  boxes.removeClass('red').eq(count).addClass('red');
}
setInterval(AddRedClass, 1000);
.container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 250px;
}
.box {
  width: 30%;
  border: 1px solid green;
  transition: background .3s linear;
}
.red {
  background: red!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="box">
    c-1
  </div>
  <div class="box">
    c-2
  </div>
  <div class="box">
    c-3
  </div>
  <div class="box">
    c-4
  </div>
  <div class="box">
    c-5
  </div>
  <div class="box">
    c-6
  </div>
  <div class="box">
    c-7
  </div>
  <div class="box">
    c-8
  </div>
  <div class="box">
    c-9
  </div>
</div>

【讨论】:

    【解决方案2】:

    jQuery 的 addClass 方法实际上会将类添加到 jQuery 集合中,因此您无需循环遍历它。

    $('.box').addClass('red');

    但是,您似乎想要为一组框设置动画。如果是这样的话,你就会遇到一系列全新的问题。

    在循环中执行所有这些操作会发生得如此之快,您可能甚至都不会注意到它。你需要做的是一个带有setTimeout的递归函数:

    animateBoxes();
    
    function animateBoxes() {
        var $boxes = $('.box'); // prefix the variable name with a $ to identify it as a jquery object, totally optional
        var boxLength = $boxes.length - 1;
        var lastChildIndex;
    
        addRedClass(0); // pass 0 in the first index
    }
    
    function addRedClass(index) {
        var $currentBox = $boxes.eq(index);
        var lastChildIndex = (index == 0) ? boxLength - 1 : index - 1;
        $boxes.removeClass('red'); // remove red class from all boxes
        $currentBox.addClass('red');
    
        setTimeout(function () { // set timeout needs a callback function, you cant just pass the function directly
            index = (index + 1) % boxLength; // increment index
            addRedClass(index);
        }, 1000);
    }
    

    我没有对其进行测试,但这是一种可以有效地完成您想要完成的工作的方法。

    【讨论】:

    • 布莱恩...感谢您的解决方案
    【解决方案3】:

    编辑:误解问题后

    要实现您想要的,您可以使用 jQuery 的 each() 函数来遍历每个元素。使用此功能,您将始终知道您当前正在访问哪个元素(通过其索引),因此您将能够检查是否需要将 red 类添加到下一个单元格。不要忘记在循环外使用计数器,也不要忘记相应地重置和计数。

    示例:https://jsfiddle.net/Ld7wc44m/4/

    ================================================ =======

    我就把这个留在这里,也许它会对某人有所帮助

    我会推荐使用 jQuery 的toggleClass()function。这样做,您不需要检查一个类是否设置在一个单元格或其前一个单元格上。 toggleClass() 只是添加一个传入的类,如果它没有附加到那个元素,或者删除它,如果它已经附加到那个元素。

    为了使其正常工作,只需将red 类手动放入每个第二个单元格,然后让算法完成其余的工作。

    虽然您的代码也获得了更好的可读性。您还可以通过调整超时功能来设置您希望颜色切换的时间。

    $(document).ready(function() {
      toggleRedClass();
    });
    
    function toggleRedClass() {
      var boxes = $('.box');
      var boxesLength = boxes.length;
    
      $.each(boxes, function(index, value) {
        $(value).toggleClass('red');
      });
    
      setTimeout(function() {
        toggleRedClass();
      }, 1000);
    }
    

    工作现场演示:https://jsfiddle.net/Ld7wc44m/3/

    【讨论】:

    • 哦,好吧,问题是要逐个更改单元格。我明白了,所以我误解了。我不好。
    【解决方案4】:

    把 JS 改成这个就可以了: http://codepen.io/anon/pen/pEPdKv

    $(document).ready(function() {
      setInterval(AddRedClass, 1000);
    });
    
    function AddRedClass() {
      // get all boxes
      var boxes = $('.box');
      // remove the current .red class and move it to the next   
      for (var i = 0; i < boxes.length; i++) {
        // check if this is a .red box
        if ($(boxes[i]).hasClass('red')) {
          // remove the current .red
          $(boxes[i]).removeClass('red');
          // move to the next box if is <9
          if (i < boxes.length - 1) {
            $(boxes[i + 1]).addClass('red');
          } else {
            // or else go back to first one
            $(boxes[0]).addClass('red');
          }
          // job done, return
          return;
        }
      }
      // if no .red box is found, then just make it the first
      $(boxes[0]).addClass('red');
      }
    

    【讨论】:

    • 稍微解释一下会很有帮助。问题是什么?您的代码如何帮助解决它?
    猜你喜欢
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多