2015-07-21 55 views
-5

我有我的主頁的JS循環。 但我不知道我怎麼能對這個詞停止「來簡單的」的Javascript:如何停止循環一詞

<h2 class = 'open'> Life Can Be <span class = 'changeable'><b>Radical</b></span></h2> 

     <script> 
      var c=0, words=['Interesting','Fun','Exciting','Crazy', 'Simple']; 
      function loop(){ 
      $('h2 span').delay(1000).fadeTo(300,0,function(){ 
       $(this).text(words[++c%words.length]).fadeTo(300,1,loop); 
      }); 
      }  
      loop(); // start it! 
     </script> 

如果您需要了解更多信息,請讓我知道,而不是反對投票。我是Javascript新手,似乎無法找到解決方案,我可能會忽略它。

回答

0

.fadeTo()將第三個可選參數complete作爲動畫完成時調用的函數,這就是發生遞歸的地方。

我們想阻止遞歸當計數器即c < words.length - 1

var c = 0, 
 
    words = ['Interesting', 'Fun', 'Exciting', 'Crazy', 'Simple']; 
 

 
function loop() { 
 
    $('h2 span').delay(1000).fadeTo(300, 0, function() { 
 

 
    $(this).text(words[++c]).fadeTo(300, 1, c < words.length - 1 ? loop : null); 
 
    }); 
 
} 
 
loop(); // start it!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<h2 class='open'> Life Can Be <span class = 'changeable'><b>Radical</b></span></h2>

+0

由於只是陣列

的最後一個元素之前。它的工作 – VVD

+0

謹慎解釋你的解決方案? –