我从DevBridge获得了Autocomplete jQuery插件或多或少的工作方式。请看这里的小提琴: https://jsfiddle.net/shalan/bcex6oaq/。这是一个简单的郊区和城市查找,用户开始在他/她的郊区打字,自动完成显示相关的建议。当用户进行选择时,它将自动使用关联的城市和邮政编码填充下面的2个只读文本框。数据结构如下所示:
var suburbData = [
{"value":"Eastcliffe", "data":{"city":"Westwood","code":"23145"}},
{"value":"Creastwich","data":{"city":"Westerlyn","code":"66365"}},
{"value":"South Woodbury Island","data":{"city":"Fairmoor","code":"89798"}},
{"value":"Faighcastle","data":{"city":"Westwood","code":"23144"}},
{"value":"Brightkeep","data":{"city":"Merrowshore","code":"08872"}},
{"value":"Summerbank","data":{"city":"Wyvernfield","code":"10467"}},
];
虽然效果很好,但我希望将建议列表格式化为:Suburb, City
,但保留调用自动完成功能的文本框中的Suburb
值。
示例:
ea
,它应该告诉我:
Eastcliffe
。如何以这种方式格式化建议列表?
答案 0 :(得分:9)
您可以使用formatResult
功能:
formatResult:function(suggestion,currentValue){}自定义函数 格式化建议容器内的建议条目,可选。
代码:
$(function() {
$('#suburb').autocomplete({
lookup: theData,
minChars: 1,
formatResult: function(suggestion, currentValue){
return suggestion.value+','+suggestion.data.city;
}
});
});
答案 1 :(得分:3)
您可以使用Autocomplete.formatResult
试试这个JS(检查完整代码的演示)
Autocomplete.formatResult = function (suggestion, currentValue) {
var pattern = '(' + utils.escapeRegExChars(currentValue) + ')';
return suggestion.value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/<(\/?strong)>/g, '<$1>') + " , " + suggestion.data.city;
};