jQuery - 使用意外的箭头键(keydown)事件和鼠标事件行为自动完成

时间:2014-04-05 16:24:43

标签: javascript jquery javascript-events

我有一个自动完成菜单,我尝试将其设置为响应鼠标和keydown事件。当我在菜单上悬停其中一个项目后按下箭头键时,问题就出现了。当我点击向上箭头键改变悬停在某个项目上时,而不是通常向上移动一个项目的行为向上移动2个项目。当我用鼠标悬停在某个项目上后按下向下箭头键时,需要2个击键才能移动

我的HTML:

<body><form action="/stocks/portfolio/" method="get" class="well" style="width:50%">
<div class="input-group" style="width:50%">
  <span class="input-group-addon"><span class="glyphicon glyphicon-search"></span>
</span>
  <input type="text" class="form-control" placeholder="Search Quote" name="q" autocomplete="off">
</div>
<div id="auto" class="list-group" style="display:none;position:absolute;width:50%"></div>

 <input type="submit" value="Search" class="btn btn-primary">
</form>

我的Javascript:

var itemSel = 0;
$(document).ready(function() {
    var result = $("input[name='q']");
    var autoComplete = $('#auto');
    result.keydown(function(event) {
        var liLength = autoComplete.children('a').length;
        if (event.keyCode == 40) {
            event.preventDefault();
            if (liLength > 0) {
                autoComplete.children('a:nth-child(' + itemSel + ')').removeClass('hover');
                itemSel++;
                autoComplete.children('a:nth-child(' + itemSel + ')').addClass('hover');
                //
                if (itemSel > liLength) {
                    itemSel--;
                }
            }
        }
        else if (event.keyCode == 38) {
            event.preventDefault();
            if (liLength > 0) {
                autoComplete.children().removeClass('hover');
                itemSel--;
                autoComplete.children('a:nth-child(' + itemSel + ')').addClass('hover');
                if (itemSel < 0) {
                    itemSel++;
                }
            }
        }
    });
    autoComplete.on('mouseover', 'a', function(event) {
        event.preventDefault();
       autoComplete.children().not($(this)).removeClass('hover');
        $(this).addClass('hover');
        itemSel = $(this).index()
    }).on('mouseout', 'a', function(event) {
        event.preventDefault();
        $(this).removeClass('hover');
        itemSel = 0;
    });
});

1 个答案:

答案 0 :(得分:0)

我实现了我犯的错误 - nth-child选择器无论出于什么原因从1开始,而不是0,我通过jQuery {{的返回值]更正了itemSel变量的赋值。 1}}并添加1