jQuery nextAll赢得';你不会在最后一个元素停止吗?
我有一个支持键盘导航的列表。然而,还有额外的jiggery扑克(本例中未包括)显示和隐藏列表中的项目。隐藏项目后,键盘导航需要继续运行,但仅适用于可见项目 我的工作做得很好。当最后一个可见项是当前项,然后用户再次按下时,就会出现问题。当前类将被删除,并尝试移动到不存在的项。向上导航时也会发生同样的情况 如何仅导航可见项并使其停止在第一个和最后一个可见项上jQuery nextAll赢得';你不会在最后一个元素停止吗?,jquery,onkeypress,css-selectors,Jquery,Onkeypress,Css Selectors,我有一个支持键盘导航的列表。然而,还有额外的jiggery扑克(本例中未包括)显示和隐藏列表中的项目。隐藏项目后,键盘导航需要继续运行,但仅适用于可见项目 我的工作做得很好。当最后一个可见项是当前项,然后用户再次按下时,就会出现问题。当前类将被删除,并尝试移动到不存在的项。向上导航时也会发生同样的情况 如何仅导航可见项并使其停止在第一个和最后一个可见项上 jQuery(文档).keydown(函数(e){ e、 预防默认值(); 如果(e.keyCode==38){//捕获向上箭头键38 va
jQuery(文档).keydown(函数(e){
e、 预防默认值();
如果(e.keyCode==38){//捕获向上箭头键38
var currentItem=jQuery(“.options”).children(“li.current”).removeClass(“current”).prevAll(':visible:first').addClass(“current”);
}否则,如果(e.keyCode==40){//Capture Arrow Down键40
var currentItem=jQuery(“.options”).children(“li.current”).removeClass(“current”).nextAll(“:visible:first”).addClass(“current”);
}
});代码>
.current{
边框:实心1px#f60!重要;
}
-
-
-
-
-
-
-
-
如果当前元素是最后一个元素,则将返回一个空的jQuery对象。您可以测试这种情况,并且仅当该类不是第一个(或最后一个)元素时,才从当前元素中删除该类:
令人惊叹的。我没意识到它返回的是一个空阵列!谢谢你,太好了。
jQuery(document).keydown(function(e) {
var currentItem = jQuery(".options").children("li.current");
if (e.keyCode == 27) { // Capture Esc key 27
e.preventDefault();
closeOptions(ddOptions, thisDd);
} else if (e.keyCode == 38) { // Capture Arrow Up key 38
e.preventDefault();
var prevItem = currentItem.prevAll(":visible:first");
if (prevItem.length) {
currentItem.removeClass("current");
prevItem.addClass("current");
}
} else if (e.keyCode == 40) { // Capture Arrow Down key 40
e.preventDefault();
var nextItem = currentItem.nextAll(":visible:first");
if (nextItem.length) {
currentItem.removeClass("current");
nextItem.addClass("current");
}
}
});