我正在尝试编写一个脚本,在按键事件上将一次显示一个数组中的一个字符串。一旦数组命中数组中的最后一项,它就会循环回到位置 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>