我有一系列的部分。使用向上和向下箭头键,我想得到当前和下一个值,不要循环,如下所示。
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
});
答案 0 :(得分: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
});
答案 1 :(得分: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>