【发布时间】:2015-09-29 16:22:22
【问题描述】:
我在我的网站中使用https://jqueryui.com/autocomplete/#multiple 来实现自动完成功能。它工作正常,现在我想搜索仅添加到文本框中的第一个字符的记录。
这是我的代码:
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css"><input type="text" id="multi"><script>$(document).ready(function() {var avail = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
];
$("#single").autocomplete({
source:avail
});
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#multi" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).autocomplete( "instance" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
avail, extractLast( request.term ) ) );
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});});</script>
【问题讨论】:
-
看看这个 SO 答案:stackoverflow.com/a/12663455/1023562 和这个演示小提琴:jsfiddle.net/Sherbrow/BwDmM/300
-
感谢 Ivan,这就是我想要的。所以现在我想用这个 stackoverflow.com/questions/12662824/… 做一个额外的思考,比如从第一个字符开始搜索记录,而不是从我搜索的字符开始的所有记录已经来了,有什么想法吗?
-
是的,答案中添加了解释。
标签: javascript jquery-ui-autocomplete