由于您的问题有点过于模糊,因此尚不清楚您要完成什么。
如果您要突出显示li
元素,请使用以下命令:
var $listItems = $('li');
$('input').keydown(function(e) {
var key = e.keyCode;
var $selected = $listItems.filter('.selected');
var $current;
if (![38, 40].includes(key)) return;
$listItems.removeClass('selected');
if (key == 40) { // Down key
if (!$selected.length || $selected.is(':last-child')) {
$current = $listItems.eq(0);
} else {
$current = $selected.next();
}
} else if (key == 38) { // Up key
if (!$selected.length || $selected.is(':first-child')) {
$current = $listItems.last();
} else {
$current = $selected.prev();
}
}
$current.addClass('selected');
});
这是小提琴:http: //jsfiddle.net/GSKpT/
如果您只是想设置input
字段的值,请将最后一行更改为:
$(this).val($current.addClass('selected').text());
这是小提琴:http: //jsfiddle.net/GSKpT/1/