我正在尝试编写一个脚本,在一个按键事件中,一次会从一个数组中显示一个字符串。一旦数组命中数组中的最后一项,它就会循环回到位置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>
答案 0 :(得分:1)
此外,对于&#34;旋转&#34;数组,试试这个:
if (e.which===13) {
$("#lyrics").html(messages[++i % messages.length]);
}