如何使这个脚本无限循环?

时间:2016-11-12 19:22:56

标签: javascript jquery html

Javascript / Jquery专家,

我有这个脚本。

的JavaScript

$(document).ready(function(){
   var number = 1;
   var timer = setInterval(function() {
     if(number == 1){str = "Professionl Designer"}
     else if(number == 2){str = "Professionl Marketer"}
     else if(number == 3){str = "Professionl Programmer"}
     else if(number == 4){str = "Professionl Developer"}    
     $("#test").html("<div>"+ str+"</div>").fadeTo(600, 0.1).fadeTo(600, 1.0);
     ++number;
     if(number == 5){
       clearInterval(timer);
     }
    }, 2500); 
});

HTML

<div id = "test"></div>

检查其fiddle

此脚本在显示最后一个标题后停止。

在连续循环中显示最后一个标题后,它应该再次显示第一个标题。

1 个答案:

答案 0 :(得分:0)

每次循环后重置数字

$(document).ready(function() {
  var pro = ["Professional Designer",
            "Professional Marketer",
            "Professional Programmer",
            "Professional Developer"];

  var number = 0;
  var timer = setInterval(function() {
  
    $("#test").html("<div>" + pro[number] + "</div>").fadeTo(600, 0.1).fadeTo(600, 1.0);
    ++number;
    if (number == 4) {
      number = 0;
    }
  }, 2500);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
</div>

或更短,使用mod %

$(document).ready(function() {
  var pro = ["Professional Designer",
            "Professional Marketer",
            "Professional Programmer",
            "Professional Developer"];

  var number = 0;
  var timer = setInterval(function() {
  
    $("#test").html("<div>" + pro[number] + "</div>").fadeTo(600, 0.1).fadeTo(600, 1.0);
    number = (number+1) %4;
    
  }, 2500);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
</div>