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를 사용하지 않는 경우 (또는 제 경우에는 사용자 정의 위젯을 개발하는 경우) 위젯을 사용하거나 코드를 자신의 위젯에 복사 할 수 있습니다.