【问题标题】:Add class sequentially to a series of elements [duplicate]将类顺序添加到一系列元素[重复]
【发布时间】:2016-10-05 13:49:28
【问题描述】:

我有一系列跨度,我想按顺序淡入。我正在尝试使用 for 循环来循环遍历跨度以通过添加一个 show 类(改变可见性)并在循环内使用 setTimeout 来稍微延迟在每个跨度上添加的类来显示它们。它似乎只将“显示”类添加到 div 的最后一个跨度,但它尝试将其添加到一个跨度 6 次(它控制台记录相同的跨度类六次)。

(我使用 javascript 而不是 jquery 来添加类,因为我收到一个错误,即 currentSeat.addClass 不是函数——另一件事我无法弄清楚)

我做错了什么??

提前致谢!

var seat = $('.seat-fillup span');
for (var i = 0; i < seat.length; i++) {
  var currentSeat = seat[i];
  setTimeout(function(){
    currentSeat.classList.add('show');
  }, 50 * i);
}
.seat-fillup span {
  visibility: hidden;
}
.seat-fillup span.show {
  visibility: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="seat-fillup">
  <span>Image here</span>
  <span>Image here</span>
  <span>Image here</span>
  <span>Image here</span>
  <span>Image here</span>
  <span>Image here</span>
</div>

【问题讨论】:

  • @adeneo 我正在写一个解决问题的答案,但是你以一个重复的结尾,OP 将难以理解。如果她无法想象为什么这不起作用,为什么她会用一个不相关的例子来理解闭包?
  • 我提名重新开放

标签: javascript jquery for-loop sequence settimeout


【解决方案1】:

需要使用闭包,使用.eq()获取元素

jQuery(function($) {
  var seat = $('.seat-fillup span');
  for (var i = 0; i < seat.length; i++) {
    (function(index) {
      setTimeout(function() {
        seat.eq(index).addClass('show');
      }, 500 * index);
    })(i)
  }
})
.seat-fillup span {
  visibility: hidden;
}
.seat-fillup span.show {
  visibility: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="seat-fillup">
  <span>Image here</span>
  <span>Image here</span>
  <span>Image here</span>
  <span>Image here</span>
  <span>Image here</span>
  <span>Image here</span>
</div>

【讨论】:

  • 完美,谢谢!现在研究闭包和 .eq() ,这似乎解决了我的几个问题。
  • 如果你打算使用 jQuery,为什么不 -> jsfiddle.net/g1by803d
【解决方案2】:

你想做(function(e){setTimeout(function(){ e.classList.add('show'); }, 50 * i);})(currentSeat);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 2013-01-04
    相关资源
    最近更新 更多