JQuery.each () Loop Cycle

I have a jQuery.each () loop that I want to continue the loop. In my current violin, these are loops, everything starts and everything, but I seem to be unable to choose the right time for different numbers. I want this loop to work regardless of the number or several elements of the list.

https://jsfiddle.net/ewsQ7/1662/

// add class first to first li
$('.js-ifeature li').first().addClass('message-first js-selected');

// add class last to last li
$('.js-ifeature li').last().addClass('message-last');

//set height
$('.js-ifeature').css('height', $('.js-ifeature li').height()+'px');

var time = 1000;
var alltheitems = $('.js-ifeature li').size();

function eachChange(){
    $('.js-ifeature li').each(function(i) {
        $(this).hide();
        $(this).delay(time * i).fadeIn(time).fadeOut(time);
        if ($(this).hasClass('message-last')) {
            setTimeout(eachChange, (alltheitems) * time);
        }
    });
}
eachChange();
+4
source share
2 answers

This is a convenient situation for a method that is not very often used shift. But since jQuery collections are not arrays, but rather array-like objects, you must pin the shift method to jQuery:

, , fadeOut , , , ... .

http://jsfiddle.net/xwuo9cpy/2/

var $featue = $('.js-ifeature'),
    $items = $featue.find('li'),
    time = 1000;

//set height
$featue.css('height', $items.first().height()+'px');
$items.hide();

// shim the shift method
$.fn.shift = Array.prototype.shift;

!function eachChange(){
    var item = $items.shift();
    $(item).fadeIn(time).fadeOut(time, eachChange);
    $items.push(item);
}();
+1

.each() . , , . - :

var time = 1000,
    current = 0,
    $lis = $('.js-ifeature li').hide(); // hide them all to start

$lis.first().addClass('message-first js-selected'); // add class first to first li
$lis.last().addClass('message-last'); // add class last to last li
$('.js-ifeature').css('height', $lis.height()+'px');

function eachChange(){
    $lis.eq(current).fadeIn(time).fadeOut(time, eachChange);
    current = (current + 1) % $lis.length;
}
eachChange();

: https://jsfiddle.net/ewsQ7/1664/

, "" , current, , .fadeOut() , jQuery, , . ( , , , message-last, .)

+1

All Articles