[英]why do minus(negative) values work with index?
I am new to jquery and basically , i decided to put Jquery to some practical use and so i build the following script : 我是jquery新手,基本上,我决定将Jquery投入实际使用,因此我构建了以下脚本:
$(function () {
$(document).on('keydown', checkey);
var index = 0,
$items = $('ul li a');
function checkey(e) {
// console.log($items);
if (e.which == 38) {
// key up
index -= 1;
};
if (e.which == 40) {
//key down
index += 1;
}
console.log(index);
$items.eq(index).trigger('focus');
}
});
useing this script you can navigate your menu useing the up and down arrow keys . 使用此脚本,您可以使用上下箭头键浏览菜单。
the fiddle is here . 小提琴在这里 。 now i have one question about the code that i have used , in particular the below line of code:
现在我对使用的代码有一个疑问,尤其是下面的代码行:
$items.eq(index).trigger('focus');
now, the index variable is incremented and decremented in my script, but when i keep pressing keyup, and the index keep decrementing and goes below 0 IE -1 , -2 , -3 , -4 ... etc , $items.eq(index).trigger('focus');
现在,索引变量在我的脚本中递增和递减,但是当我继续按下keyup时,索引不断递减并低于0 IE -1,-2,-3,-4 ...等,
$items.eq(index).trigger('focus');
, this line still works , i was't expecting it to work with negative values , i was expecting it only to work from 0-4 . ,这行仍然有效,我没想到它会以负值工作,我只是希望它能从0-4开始工作。
so how and why do negative values work with the below statement : 所以负值如何以及为什么与以下语句一起工作:
eg. $items.eq(-2).trigger('focus'); ??
NOTE : in the fiddle please check the console and experiment with arrow up and arrow down, to understand what i am talking about . 注意:在小提琴中,请检查控制台并尝试使用向上箭头和向下箭头,以了解我在说什么。
From the jQuery API documentation : 从jQuery API文档中 :
Providing a negative number indicates a position starting from the end of the set, rather than the beginning.
提供负数表示位置是从集合的末尾开始,而不是开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.