jQuery - Adding classes to elements inside array with delay

懵懂的女人 提交于 2019-12-13 15:26:33

问题


I have an array that contains some elements from my page.

Now I need a function that literates through the array and adds a class bold to each element. The problem is that once the class is added, some time has to pass. Then bold has to be removed and needs to be applied to the next element, resulting in a "wave" motion.

I've tried to do it like this:

$.each(tdArr, function(i, v) {
  v.addClass("bold");
  setTimeout(function(){
    v.removeClass("bold");
  }, 900)
})

The problem with that code is that bold is added to all elements at once and gets removed 900 ms later, again from all elements at the same time.

What do I have to do to add a delay between the separate actions?


回答1:


I think you need to approach this slightly differently, as setTimout returns straight away it wont stop the next element being set as bold.

You could do it with a method like this:

function bold(i){
    if(i>0){
        $tdArr.eq(i-1).removeClass('bold');
    }
    if(i == $tdArr.length){
        return;
    }
    $tdArr.eq(i).addClass('bold')   

    setTimeout(function() { bold(i+1) },900);
}

And then to call it you'd just need to call bold(0):

Live example: http://jsfiddle.net/rJGjZ/




回答2:


Try this:

$.each(tdArr, function(index, element) {
  var $elem = $(element);
  $elem.addClass("bold");
  setTimeout(function(){
    $elem.removeClass("bold");
  }, 900)
})

The second param is not a jQuery element and you need convert him




回答3:


Would something like this work for you ?

function Bold(element) {
  $(element).addClass("bold"); // we bold the current tdArr
  setTimeout(function(){
    var nextSibling = $(element).next("td") // (if the tdArr are "td" tags) we find the next td brother of this one
    if (!!nextSibling) Bold(nextSibling); // if there is a brother, repeat the function on him after 900ms
  }, 900)
}

Bold(myfirsttd);



回答4:


Increase the delay as you iterate the array, and make sure to wrap your element in jQuery if it's not already wrapped. If it's a collection of jQuery elements, then use each to iterate.

var delay = 900

$els.each(function(){
  var $this = $(this)
  setTimeout(function(){
    $els.removeClass('bold')
    $this.addClass('bold')
  }, delay+=900)
})

Otherwise, I would use for and wrap the element in jQuery.

for (var i=0, l=arr.length, d, prev; i<l; i++; d+=900) {
  prev = arr[i-1]
  setTimeout(function(){
    if (prev) $(prev).removeClass('bold')
    $(arr[i]).addClass('bold')
  }, d)
}


来源:https://stackoverflow.com/questions/11797668/jquery-adding-classes-to-elements-inside-array-with-delay

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!