2013-10-16 66 views
0

我想写一个脚本,在按键事件将从一个数组中显示一次一个字符串。一旦数组碰到数组中的最后一项,它将循环回0位置,从而创建一个连续的循环。现在我有一个脚本会一次显示一个项目,但它不是正确的方式,也不会循环回到开始。Jquery/Jscript:显示从阵列中的字符串旋转阵列

我不希望它打印每个项目作为一个长长的清单,但在按键显示第一个字符串,并在接下来的按键,清除DIV,并显示在它的下一个字符串的地方

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="UTF-8"> 
    <title>Rotating Messages</title> 
    <link href="stylesheets/site.css" rel="stylesheet"> 

    <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script> 
    <script> 
     var i = 0; 
     var messages=["Tonight I\'m gonna have myself a real good time ", 
       "I feel alive and the world it\'s turning inside out Yeah! ", 
       "I\'m floating around in ecstasy ", 
       "So don\'t stop me now don't stop me ", 
       "Cause I\'m having a good time having a good time ", 
       "I\'m a shooting star leaping through the skies ", 
       "Like a tiger defying the laws of gravity ", 
       "I\'m a racing car passing by like Lady Godiva ", 
       "I'm gonna go go go ", 
      "There\'s no stopping me "] 


$(document).ready(function() { 
    $(document).keypress(function(e) { 

     if (e.which===13) { 
      if(i<=messages.length) { 
       $("#lyrics").append(messages[i]); 
        i=i+1; 
      } 
     } 
    }); 
    }); 




     </script> 

    <body> 
    <div id="wrapper"> 
    <header class="title"> 
    <h1> Fun with Arrays!</h1> 
    <div id="lyrics"> </div> 

    </body> 

Demo

回答

1

此外,对于 “旋转” 数组,试试这个:

if (e.which===13) { 

      $("#lyrics").html(messages[++i % messages.length]); 
    } 

小提琴:http://jsfiddle.net/wmqcd/35/

+0

也可以,而不是在我的函数中嵌套第三个if语句 – nope