jQuery UI オートコンプリート ウィジェットをご覧になることをお勧めします。彼らのコードベースは他のほとんどのものよりも成熟しているため、彼らはそこでほとんどのケースを処理しました.
以下はデモページへのリンクで、動作を確認できます。http://jqueryui.com/demos/autocomplete/#default
ソースを読んで、彼らがそれをどのように解決したかを見ることで、最大の利益が得られます。ここで見つけることができます: https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.autocomplete.js。
基本的に、それらはすべて実行し、 にバインドしinput, keydown, keyup, keypress, focus and blur
ます。次に、のようなあらゆる種類のキーに対して特別な処理を行いますpage up, page down, up arrow key and down arrow key
。テキストボックスの内容を取得する前にタイマーが使用されます。ユーザーがコマンドに対応しないキー (アップ キー、ダウン キーなど) を入力すると、約 300 ミリ秒後にコンテンツを探索するタイマーがあります。コードでは次のようになります。
// switch statement in the
switch( event.keyCode ) {
//...
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
// when menu is open and has focus
if ( this.menu.active ) {
// #6055 - Opera still allows the keypress to occur
// which causes forms to submit
suppressKeyPress = true;
event.preventDefault();
this.menu.select( event );
}
break;
default:
suppressKeyPressRepeat = true;
// search timeout should be triggered before the input value is changed
this._searchTimeout( event );
break;
}
// ...
// ...
_searchTimeout: function( event ) {
clearTimeout( this.searching );
this.searching = this._delay(function() { // * essentially a warpper for a setTimeout call *
// only search if the value has changed
if ( this.term !== this._value() ) { // * _value is a wrapper to get the value *
this.selectedItem = null;
this.search( null, event );
}
}, this.options.delay );
},
タイマーを使用する理由は、UI が更新される機会を得るためです。Javascript の実行中は UI を更新できないため、遅延関数を呼び出します。これは、(そのコードで使用される) テキストボックスにフォーカスを維持するなど、他の状況でうまく機能します。
したがって、jQuery UI を使用していない場合 (または私の場合はカスタム ウィジェットを開発している場合) は、ウィジェットを使用するか、独自のウィジェットにコードをコピーできます。