我需要在“活动”项目中使用Jquery中的循环

时间:2016-06-28 19:05:44

标签: javascript jquery loops

我现在使用的是JavaScript,我希望将每个<li>的循环设置为“有效”,从n°1到<li> n°4再次开始,每次都是n°1秒。

我现在有这个代码:

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')
    }

    }
});

请帮助我!

2 个答案:

答案 0 :(得分:0)

  • 在测试==时使用===length,因为=将充当assignment operator,并且始终会将其评估为true < / LI> 分配else变量
  • 后,应关闭
  • $next_selected

&#13;
&#13;
$(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');
  }
});
&#13;
.active {
  color: green;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分: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);