2014-10-31 76 views
0

我有一个部分的数组。使用向上和向下箭头键,我想获得当前值和下一个值,并且不循环,如下所示。jQuery - 向上和向下键从数组中获取值

var sections = [ "A", "B","C","D"]; 

$(document).keydown(function(e){ 

    var k= e.which; 

    if(k==40){ sections.push(sections.shift()); } 

    else if(k==38){ sections.unshift(sections.pop()); } 

    $('body').html('You just went to ' + sections[0]); // current section. 
    // How to return the previous section that I was in? 
    // For example: You just left section A then went to section B 
    // Do not loop, return: You just reached end/beginning 
}); 

工作小提琴:http://jsfiddle.net/9977ov2x/

+0

所以你的代码工作,你认为它需要审查?如果是的话,张贴在http://codereview.stackexchange.com/ – undefined 2014-10-31 03:44:42

+0

@Vohuman不,检查第二和第三//评论 – 2014-10-31 03:46:38

回答

1

尝试

var sections = ["A", "B", "C", "D"]; 
var i = 0; 
var $pre = $('p'); 
var $now = $('span'); 
var $next = $('div'); 
$(document).keydown(function (e) { 

    var k = e.which; 
    var pretmp = sections[i] ; 
    //Next is same to it you put the variables to the if block below and then echo 2 line in some html tag " if press up will be " and " else will be " so you will have 2 next tmp var i assume it next1 and next2 
    if (k == 40) { 
     i++; 
     // next1 
    } else if (k == 38) { 

     i--; 
     //next2 
    } 

    if (i >= sections.length) { 
     i = 0; 
    } else if (i < 0) { 
     i = sections.length - 1; 
    } 
    $pre.html('Previous is ' + pretmp); 
    $now.html('You just went to ' + sections[i]); // return the current section. 
    // How to return the previous section? 
    // For example: You just left section A then went to section B 
    // Also stop if I'm at the end or begaing then return: You just rech end/beginig 
}); 
体内

和HTML

<p></p><span></span><br/><div></div> 
2
var sections = [ "A", "B","C","D"]; 
var i=0; 
$(document).keydown(function(e){ 

    var k= e.which; 

    if(k==40){ i++; } 

    else if(k==38){ i--; } 

    if(i>=sections.length){ 
    i=0; 
    } 
    else if(i<0) 
    { 
    i=sections.length-1; 
    } 

    $('body').html('You just went to ' + sections[i]); // return the current section. 
    // How to return the previous section? 
    // For example: You just left section A then went to section B 
    // Also stop if I'm at the end or begaing then return: You just rech end/beginig 
}); 

http://jsfiddle.net/9977ov2x/2/

+0

好吧,这是一样的..我需要返回当前和下一节。检查评论让我。 – 2014-10-31 03:49:22

+0

认真吗?在if块中,你做你想做的事......这并不意味着你已到达结尾或开始 – Baz1nga 2014-10-31 03:54:53

+0

我知道这很好,那么我离开的部分呢?节[i]将返回新的值,我需要返回之前返回的前一个 – 2014-10-31 04:03:48