我有这个代码:
<script type="text/javascript">
var myList = [ "Avellino", "Enna", "Frosinone" ];
$("#myTextBox").autocomplete({
source: myList,
appendTo: "#myOwnMenuProvince"
});
</script>
现在,如果我输入e
,我只想看到列表中以e
开头的单词,而不是包含e
。因此,在上面的示例中,只有 Enna
。
我该怎么做?
最佳答案
默认情况下,插件使用方法$.ui.autocomplete.filter
。此方法使用正则表达式对数据的标签/值属性执行 grep 操作,并返回过滤后的数据。让我们从中得到启发来进行过滤。
要使用您自己的过滤方法,请使用 source
选项作为回调。
request
参数是一个包含一个属性term
的对象。它包含要搜索的文本,基本上是输入字段的值。因此,如果您在输入字段中输入“en”,request.term
将具有该值。response
参数是回调。你调用它,传递过滤后的数据,来显示数据,基本上显示结果弹出菜单。
基本上,您将过滤数据并将过滤后的数组传递给“response”回调。
这是一种方法:
$("#myTextBox").autocomplete({
source: function(request, response) {
// filter your data
var data = $.grep(myList, function(value) {
return value.substring(0, request.term.length).toLowerCase() == request.term.toLowerCase();
});
// pass it to the response callback for display
response(data);
}
});
<强> DEMO
关于jquery - 自动完成 : How can I change the result list with only elements that start with input-word?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9392953/