自动完成:只有当用户键入制表键时,才关注第一个项目

Autocomplete: first item focused only when the user type on tab key

本文关键字:制表键 项目 第一个 用户      更新时间:2023-09-26

通过使用jqueryUi autocomplete,我希望只有当用户键入tab key时,第一个项目才会自动聚焦
我应该如何执行此任务
使用指定的autoFocus option true初始化自动完成不符合我的目的!

有什么想法吗?


这是我的密码
有关更多详细信息,请参阅评论。

    element.autocomplete({
        minLength: 3,
        // the following option "autoFocus = true"
        // make the first item focused when the user type the first 3 letters
        // I would like the first item focused only when I type on TAB 
        autoFocus: false,
        source: function (request, response) {
            // some code
        }
    }).data('autocomplete')._renderItem = renderItem;
    // the following piece of code works only when I type the first three letters,
    // If I type four letters and then tab it does not work!
    element.on('keyup', function (event) {
        if (event.keyCode === 9) {
            element.autocomplete( "option", "autoFocus", true );
        }
    });

是的,autoFocus不会做你想做的事。相反,您可以伪造用户在想要选择项目时通常必须执行的按键。

element.keydown(function(e){
   if( e.keyCode != $.ui.keyCode.TAB ) return; // only pay attention to tabs
   e.keyCode = $.ui.keyCode.DOWN;   // fake a down error press
   $(this).trigger(e);
   e.keyCode = $.ui.keyCode.ENTER;  // fake select the item
   $(this).trigger(e);
});

演示:http://jsfiddle.net/uymYJ/8/