【问题标题】:Keypress to display string array jquery按键显示字符串数组jquery
【发布时间】:2013-10-16 08:49:53
【问题描述】:

我有一个字符串数组,我想在按键上一次显示一个。我有一个带有歌词类的空 div。使用

$(document).keyup(function(e){
    if (event.which==13)
    ...

我只是对这里的语法感到困惑,我将如何指定此事件将我的数组打印到我的 div。我在这里省略了大部分脚本,因为这是我需要帮助的唯一部分

这里的 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 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"
        ];
    </script>
</head>
<body>
    <div id="wrapper">
        <header class="title">
            <h1> Fun with Arrays!</h1>
            <div class="lyrics"></div>
            ...

我只是对如何使用按键打印到空 div 感到困惑

【问题讨论】:

  • 也发布您的 html 代码。
  • 你使用e然后使用e.which

标签: javascript jquery arrays syntax keypress


【解决方案1】:

将消息放入队列中,一次显示一个字符串。 shift 函数允许您遍历消息数组。

在下面的示例中,每次用户按下回车键后,都会在 div 中追加一个新行,类为 lyrics

var queue = messages;

$(document).keyup(function(e){
  if (e.which == 13) {
     var val = queue.shift(); 
     $(".lyrics").append(val); 
  }
}

【讨论】:

    【解决方案2】:

    试试这个:

      var i=0;
    $(document).keypress(function(e) {
         var arrofobject = ["197","Damskie","198","M\u0119skie"];
         var len=arrofobject.length;
     if (e.which == 13) {
         if(i<=len)
         {
        $(".lyrics").append(arrofobject[i]);
             i=i+1;
         }
       }
    });
    

    查看DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多