2016-06-28 18 views
1

我現在在JavaScript中,我想做一個循環設置每個<li>與類「活躍」從n°1到<li> n°4並再次開始n° 1每3秒。我需要一個循環jquery從'活躍'項目

我有這樣的代碼至今:

HTML

<ul class="collection"> 
    <li id="first" class="collection-item active">Desplazate hacia la pestaña <strong>HORARIOS</strong>.</li> 
    <li id="second" class="collection-item ">Ingresa tu N° de documento.</li>  
    <li id="third" class="collection-item ">Presiona el botón <strong>INGRESAR</strong>.</li> 
    <li id="four" class="collection-item "><strong>LISTO!</strong> Ahora puedes ver los horarios de la semana.</li> 
</ul> 

的JavaScript

$(document).ready(function(){ 


    setInterval(animacion,3000); 

    function animacion(){ 
     $currently_selected = $('li.active') 

    // Loop back to first sibling if on the last one. 
     if ($currently_selected.next().length = 0){ 
     $next_selected = $currently_selected.siblings().first() 
    } else { 
     $next_selected = $currently_selected.next() 

     $currently_selected.removeClass('active') 
     $next_selected.addClass('active') 
    } 

    } 
}); 

請幫幫我!

回答

0
  • 使用=====而測試length=將作爲assignment operatortrue
  • else塊應的$next_selected可變

$(document).ready(function() { 
 
    setInterval(animacion, 3000); 
 

 
    function animacion() { 
 
    $currently_selected = $('li.active'); 
 
    if ($currently_selected.next().length == 0) { 
 
     $next_selected = $currently_selected.siblings().first(); 
 
    } else { 
 
     $next_selected = $currently_selected.next(); 
 
    } 
 
    $currently_selected.removeClass('active'); 
 
    $next_selected.addClass('active'); 
 
    } 
 
});
.active { 
 
    color: green; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<ul class="collection"> 
 
    <li id="first" class="collection-item active">Desplazate hacia la pestaña <strong>HORARIOS</strong>.</li> 
 
    <li id="second" class="collection-item ">Ingresa tu N° de documento.</li> 
 
    <li id="third" class="collection-item ">Presiona el botón <strong>INGRESAR</strong>.</li> 
 
    <li id="four" class="collection-item "><strong>LISTO!</strong> Ahora puedes ver los horarios de la semana.</li> 
 
</ul>
分配後關閉它都會被評估

+0

非常感謝!這正是我期待的! –

0

繼承人一種方式來做到這一點。

setInterval(function(){ 
var items = $('.collection li'); 
items.each(function(ind,val){ 
    if($(this).hasClass('active')){ 
      $(this).removeClass('active'); 
      if(ind !== items.length - 1) {     
       items.eq(ind + 1).addClass('active'); 
       return false; 
      }else{ 
       items.eq(0).addClass('active'); 
       return false; 
      } 
    } 
}); 
},3000);