问题描述
我有一系列颜色。使用向上和向下箭头键,我想循环遍历数组并将当前数组值作为类添加到div。
I have an array of colors. using the up and down arrow keys, I would like to loop through the array and add the current array value as a class to a div.
var colors = [
"red",
"green",
"blue"
];
我想将当前值存储为变量并使用jQuery .addClass附加一个当前类到div。作为一个jQuery新手,这里的任何帮助都会很棒!
I would like to store the present value as a variable and use the jQuery .addClass to append a the current class to a div. As a jQuery newcomer, any help here would be fantastic!
推荐答案
1。使用提醒 %
循环索引计数器
var colors = ["red", "green", "blue"],
i = 0,
n = colors.length;
$(document).keydown(function(e){
var k = e.which;
if(k==38||k==40){
i = (k==38? ++i : --i) <0? n-1 : i%n;
$('#test').attr('class', colors[i]);
}
});
2。在内部操作数组
另一个有趣的(不太复杂的)方法,不使用当前索引计数器
是操纵数组它只需将最后一个键推到第一个位置(或反向,从头到尾)并始终获取[0]索引键:
2. Manipulating internally the Array
Another interesting (less complicated) way to do it, without using a current index counter
is to manipulate the Array it-self by simply pushing the last key to the first position (or inverse, first to last) and always get the [0] index key:
var colors = ["red", "green","blue"];
$(document).keydown(function(e){
var k = e.which;
if(k==38||k==40){
if (k==38) colors.push(colors.shift());
else if (k==40) colors.unshift(colors.pop());
$('#test').attr('class', colors[0]);
}
});
这篇关于上下键来循环遍历数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!