【问题标题】:Jquery/Jscript: Displaying a rotating array of strings from arrayJquery/Jscript:从数组显示旋转的字符串数组
【发布时间】:2013-10-16 21:23:07
【问题描述】:

我正在尝试编写一个脚本,该脚本在按键事件中将一次从数组中显示一个字符串。一旦数组命中数组中的最后一项,它就会循环回到位置 0,从而创建一个连续循环。现在我有一个脚本可以一次显示每个项目,但它的行为方式不正确,也不会循环回到开头。

我不希望它将每个项目打印为一个长列表,而是在按键上显示第一个字符串,在下一次按键时,清除 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

【问题讨论】:

    标签: javascript jquery arrays string keypress


    【解决方案1】:

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

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

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

    【讨论】:

    • 同样有效,代码更简洁,而不是在我的函数中嵌套第三个 if 语句
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    • 2011-02-06
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多