这是一个解决方案。它可能需要一些调整才能在同一页面上使用多个自动完成功能,但它可以使用一个:
(function( $ ) {
$.extend($.ui.autocomplete.prototype, {
_createSelection: function($input, start, end) {
// get a reference to the input element
var field = $input.get(0);
// set the selection (browser specific methods)
if( field.createTextRange ){
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", end);
selRange.select();
} else if( field.setSelectionRange ){
field.setSelectionRange(start, end);
} else {
if( field.selectionStart ){
field.selectionStart = start;
field.selectionEnd = end;
}
}
field.focus();
},
_autoFill: function($input, sValue) {
// here 'this' is the plugin itself
// if the last user key pressed was backspace, don't autofill
if (this._lastKeyPressCode != 8) {
// fill in the value (keep the case the user has typed)
$input.val($input.val() + sValue.substring(this._previousValue.length));
// select the portion of the value not typed by the user (so the next character will erase)
this._createSelection($input, this._previousValue.length, sValue.length);
}
},
_previousValue: '',
_lastKeyPressCode: null
});
$( ".ui-autocomplete-input" )
.live( "keyup", function() {
var $this = $(this),
autocomplete = $this.data('autocomplete'),
key;
autocomplete._lastKeyPressCode = key = event.which;
// do nothing on backslash/command keys
if( key == 46 || (key > 8 && key < 32) )
return autocomplete.menu.deactivate();
// check value is different
var v = $this.val();
if (v == autocomplete._previousValue)
return;
// save value
autocomplete._previousValue = v;
})
.live( "autocompleteopen", function() {
var $this = $(this),
autocomplete = $this.data( "autocomplete" ),
menu = autocomplete.menu;
// check the 'selectFirst' setting
if ( !autocomplete.options.selectFirst ) {
return;
}
// activate the menu
menu.activate( $.Event({ type: "mouseenter" }), menu.element.children().first() );
// set the autoFill
autocomplete._autoFill($this, menu.element.children().first().text());
});
}( jQuery ));
$('.for-autocomplete').autocomplete({selectFirst: true, source: ['aa','absolution','borinage','baba']});
初始化自动完成小部件,您必须添加新选项selectFirst: true/false
.
autofill 和 createSelection 方法取自此自动完成插件 http://www.pengoworks.com/workshop/jquery/autocomplete.htm现场活动的结合就是受此启发post https://stackoverflow.com/questions/2933713/add-autofill-capabilities-to-jquery-ui-1-8-1.
Enjoy
Edit
我已经调整了代码,现在它与 jQuery UI 自动完成小部件完全集成。它可以与同一页面上的插件的多个实例一起使用。
:o)