上下键来循环遍历数组 [英] Up and down keys to loop through array

查看:78
本文介绍了上下键来循环遍历数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列颜色。使用向上和向下箭头键,我想循环遍历数组并将当前数组值作为类添加到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。使用提醒

循环索引计数器

http://jsbin.com/howon/5/edit

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:

http://jsbin.com/jojupo/3/edit

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]);
  }
});

这篇关于上下键来循环遍历数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆