Javascript 选择列表元素(捕获向下/向上箭头)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11400269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:43:20  来源:igfitidea点击:

Selecting List Element (capturing down/up arrow)

javascriptjquerydrop-down-menudom-eventskeypress

提问by I-M-JM

I have following HTML structure ('ul li' are rendered as drop-down/select)

我有以下 HTML 结构('ul li' 呈现为下拉/选择)

<input id="input_city" type="text" />

<div class="suggestions">
 <ul>
  <li value="0" name="New York">New York</li>
  <li value="1" name="London">London</li>
  <li value="2" name="Paris">Paris</li>
  <li value="3" name="Sydney">Sydney</li>
 </ul>
</div>

Need JavaScript/jQuery code to capture down arrow key press event (on input) which will select first 'li' element

需要 JavaScript/jQuery 代码来捕获向下箭头键按下事件(输入时),这将选择第一个 'li' 元素

Consecutive down key select next 'li' elements; and up key select previous 'li' elements.

连续向下键选择下一个'li'元素;和向上键选择以前的 'li' 元素。

回答by Joseph Silber

Since your question is a little too vague, it's not exactly clear what you're trying to accomplish.

由于您的问题有点过于模糊,因此不清楚您要完成的任务。

If you're trying to highlight the lielements, use this:

如果您要突出显示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');
});?

Here's the fiddle: http://jsfiddle.net/GSKpT/

这是小提琴:http: //jsfiddle.net/GSKpT/



If you're just trying to set the value of your inputfield, change the last line to this:

如果您只是想设置input字段的值,请将最后一行更改为:

$(this).val($current.addClass('selected').text());

Here's the fiddle: http://jsfiddle.net/GSKpT/1/

这是小提琴:http: //jsfiddle.net/GSKpT/1/

回答by Split Your Infinity

You can use MousetrapJSfor this. Here an example how you could implement the down key. First add the class selected to the first list item.

您可以为此使用MousetrapJS。这是一个如何实现向下键的示例。首先将选择的类添加到第一个列表项。

Mousetrap.bind('down', function() {
    var next = $(".suggestions  li.selected").removeClass("selected").next();
    if (next.length) {
       next.addClass("selected");
    } else {
       $(".suggestions li").first().addClass("selected");
    }
});