[英]How can I change the result filter in Autocomplete?
我不想進行文字匹配,而是通過正則表達式選擇結果。
我可以覆蓋自動完成的默認行為來完成此操作,還是需要替代結構?
有一種內置方法可以做到這一點:只為自動完成小部件中的source
選項提供一個函數:
var items = ['Foo', 'Bar', 'Hello', 'Goodbye', '1234'];
$("#autocomplete").autocomplete({
source: function(request, response) {
// The term the user searched for;
var term = request.term;
// Extract matching items:
var matches = $.grep(items, function(item, index) {
// Build your regex here:
return /\d+/.test(item);
});
// let autocomplete know the results:
response(matches);
}
});
請注意,由於我使用的簡單正則表達式,此示例將始終返回“1234”。 更有用的可能是根據術語(也可能)構建正則表達式。
這實際上與小部件本身過濾結果的方式非常相似。 檢查此行以獲取過濾器功能和此行,以查看在提供數組作為source
選項時如何調用它。
我創建了一個示例,其中只呈現標簽中包含字符串'jQuery'的結果:
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"}
];
$("input").autocomplete({
source: projects
}).data("autocomplete")._renderItem = function(ul, item) {
// this is where you can implement your regex
if (item.label.indexOf("jQuery") !== -1) {
return $("<li></li>").data("item.autocomplete", item).append("<a>" + item.label + "<br>" + item.desc + "</a>").appendTo(ul);
}
};
你可以覆蓋jQueryUI的自動完成的默認行為。 在您的控制器中,您應該編寫服務器端邏輯以生成結果集。 jQuery autcomplete默認使用q
作為參數。 使用它可以獲取值並生成將成為列表的結果集。 我想這會給你一個想法。 自動填充只顯示每個鍵盤上的結果。 你應該注意顯示邏輯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.