我需要使用按键增加我的数组。我可以获取要显示的数组的第一个元素,但是当我按下另一个键时无法显示数组的其他元素。
我已经使用警报来获取使用按键显示的消息,并且可以获取要显示的数组中的第一个元素,但是当我再次按下该键时无法显示该数组的其他元素。
function display_phrase() {
var arrayPhrase = ['Relax!', 'Dont Do It!', 'Chill!', 'Take It Easy!', 'Do It!', 'Panic!', 'Beat It!','Forget About It!','Wooooo!','Oh Bother!'];
var arrayCounter = 0;
var arrayPosition = (arrayCounter % arrayPhrase.length);
$("#display_phrase").html("<h1>" +arrayPhrase[arrayPosition] +".</h1>");
}
var arrayCounter = 0;
$(document).ready(function() {
$('body').keypress(function() {
display_phrase();
arrayCounter++;
});
});
在您的版本中,display_phrase
使用同名的局部变量屏蔽全局arrayCounter
变量。要解决此问题,请删除本地var arrayCounter = ...
并将声明保留在更高的范围内。
例如:
var arrayPhrase = ['Relax!', 'Dont Do It!', 'Chill!', 'Take It Easy!', 'Do It!', 'Panic!', 'Beat It!','Forget About It!','Wooooo!','Oh Bother!'];
var arrayCounter = 0;
function display_phrase() {
var arrayPosition = (arrayCounter % arrayPhrase.length);
$("#display_phrase").html("<h1>" +arrayPhrase[arrayPosition] +".</h1>");
}
...
删除函数内的arrayCounter
。由于您具有全局变量和具有相同名称的局部变量,因此局部变量优先于函数内部。
只需删除它,让它使用全局的。
function display_phrase() {
var arrayPhrase = ['Relax!', 'Dont Do It!', 'Chill!', 'Take It Easy!', 'Do It!', 'Panic!', 'Beat It!', 'Forget About It!', 'Wooooo!', 'Oh Bother!'];
//var arrayCounter = 0;
var arrayPosition = (arrayCounter % arrayPhrase.length);
$("#display_phrase").html("<h1>" + arrayPhrase[arrayPosition] + ".</h1>");
}
var arrayCounter = 0;
$(document).ready(function() {
$('body').keypress(function() {
display_phrase();
arrayCounter++;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="display_phrase"></div>