遍历所有的 div 并更新元素

3

我有一个包含10个元素的数组,在页面加载时有5个div,每个div都会从这个数组中获取一个值,然后使用setInterval()函数,每1秒钟更新一次剩余数组元素的div值。

问题在于我只想使用一个foreach循环值从#8开始更新而不是从#6开始,并且最后两个div没有被更新。

示例代码:http://jsfiddle.net/90h7045b/

var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  first = data.slice(0, 5),
  second = data.slice(5),
  count = 0;

//update first 5 on page load
$.each($('.wrap'), function(i) {
  $(this).find('.title').html(first[i]);
});

$('#container .wrap:first').addClass('current');

//it does not work with `.wrap`
$.each($('#container'), function() {
  (function($set) {
    var interv = setInterval(function() {
      count++;
      var $cur = $set.find('.current');
      $cur.removeClass('current');

      $cur.find('.title').html(second[count]);
      var $next = $cur.next().length ? $cur.next() : $set.children().eq(0);
      $next.addClass('current');
      if(count == 4)
        clearInterval(interv);
    }, 1000);
  })($(this));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div class="wrap"><div class="title"></div></div>
  <div class="wrap"><div class="title"></div></div>
  <div class="wrap"><div class="title"></div></div>
  <div class="wrap"><div class="title"></div></div>
  <div class="wrap"><div class="title"></div></div>
</div>

2个回答

6
您可以简化您的代码。您真的需要两次切割数组吗?使用一个变量作为您的分割索引并使用它不是更好吗?另外,不要使用`setInterval`而是使用`setTimeout`。
以下是示例: Fiddle: http://jsfiddle.net/abhitalks/90h7045b/42/ 代码片段:

var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    $wrap = $(".wrap"), 
    split = 5;

$wrap.each(function (idx) {
    var self = $(this), 
        elem = idx + split,
        timer = ((idx+1) * 1000);
    
    $(this).find('.title').html(data[idx]);
    setTimeout(function () {
        self.find('.title').html(data[elem]);
    }, timer);
});
body { text-align:center; }
.wrap {
    display: inline-block;
    background: #f3f3f3; color: #f8008c;
    padding: 5px; margin:5px; width: 64px; height:64px;
    line-height: 64px; border-radius:37px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
    <div class="wrap"><div class="title"></div></div>
    <div class="wrap"><div class="title"></div></div>
    <div class="wrap"><div class="title"></div></div>
    <div class="wrap"><div class="title"></div></div>
    <div class="wrap"><div class="title"></div></div>
</div>


哇,非常感谢! - M1X

2
我相信你想要的是在代码执行完后,div显示6到10。我找到了一个简单的解决方案,即将计数变量从-2开始,因为你的代码在循环中更新得太晚了。
请将初始计数变量赋值更改为以下代码:
count = 0;

to:

count = -2;

JsFiddle示例:http://jsfiddle.net/larryjoelane/90h7045b/18/

(该示例为IT技术相关内容,需要您自行查看)

我认为存在问题,因为您无法将计数器设置为-2。 - M1X
看一下我发布的 JSFiddle 链接,让我知道它是否给你想要的结果。 - Larry Lane
这正是我想要的,但我能否只在同一个foreach循环中包装它?@Larry Lane - M1X
1
让我调查一下,您希望它在单个JQuery each函数中工作? - Larry Lane
我相信abhitalks的解决方案将集合你所需的一切。 - Larry Lane
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接