1

通过使用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 );
        }
    });
4

1 回答 1

2

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

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/

于 2012-08-20T14:52:48.413 回答