簡體   English   中英

jQuery / Jscript:顯示來自數組的旋轉字符串數組

[英]Jquery/Jscript: Displaying a rotating array of strings from array

我正在嘗試編寫一個腳本,該腳本在按鍵事件中一次從數組中顯示一個字符串。 一旦數組命中數組中的最后一項,它就會循環回到位置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>

演示

另外,對於“旋轉”數組,請嘗試以下操作:

    if (e.which===13) {

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM