jquery:输入标签中的向上/向下箭头键选择了<select>项目

Ove*_*eer 3 jquery

我知道那里有数百个类似的问题,相信我,当我说我读了很多这些问题时,但问题仍然存在.如果我有一个输入标签id ="input1"和一个select id ="list1",我想在输入组件中按下向上/向下箭头键,以相应地向上或向下移动选择列表中的选定选项.

我已设置select标记的值,以便选择选项列表中的第一项,但此代码不起作用.我已经检查了keydown事件的绑定工作正常,我已经尝试在select组件上触发keyup/keydown/keypress(所有尝试的)事件之前暂时将焦点设置到select.我是否应该专注于选择组件,然后在触发按键事件之前触发选择或更改事件?

        deflectEvent = function(event) {
            if((event.which == $.ui.keyCode.UP) ||
              (event.which == $.ui.keyCode.DOWN)) {
                //$('#list1').focus(); //.focus().click();
                $('#list1').trigger(event);
                //$('#input1').focus();
                return false;
            };
        }
        jQuery(function($){$('#input1').bind('keydown',deflectEvent)});
Run Code Online (Sandbox Code Playgroud)

我观察到的事情,是错误的,没有.在IE8上,我可以按箭头键并使用$('#list1')获得焦点移动.focus().focus().click(); 但在Chrome上,我甚至无法做到这一点.

我知道jquery模拟插件,虽然我没有设法找到它的任何使用示例.例如,如果您模拟按键事件,如何指定按下了哪个键?

谢谢.

Sam*_*tin 7

这是你追求的吗?

$(document).ready(function(){
deflectEvent = function(event) {
    var noOfListItems = $("#list1 > option").length-1;
    var curListItem = $("#list1")[0].selectedIndex;
    if(event.which == $.ui.keyCode.UP) {
         // Decrement the selection by one, unless that will be less than zero, then go to the last option
        var nextListitem = (curListItem-1 < 0) ? noOfListItems : curListItem-1;
        $("#list1")[0].selectedIndex = nextListitem;
    }
    if(event.which == $.ui.keyCode.DOWN){
         // Increment the selection by one, unless that will be more than the number of options, then go to the first option
        var nextListitem = (curListItem+1 > noOfListItems) ? 0 : curListItem+1;
        $("#list1")[0].selectedIndex = nextListitem;
    }
}

jQuery(function($){$('#input1').bind('keydown',deflectEvent)});
});
Run Code Online (Sandbox Code Playgroud)

jsFiddle版本