我在Bootstrap的Typeahead中为建议定义了一个自定义模板,如下所述。但是当我选择任何建议时,我只会在输入中得到国家名称。因为我已经通过国家在displayKey参数。无论如何,我可以在输入中选择国家和城市名称(与模板相同)?
这里是JsFiddle: http://jsfiddle.net/geekowls/agrg3xhj/
我还阅读了Typeahead网站上的示例。但没找到任何相关信息。我只知道displayKey参数可以接受一个函数。
$(document).ready(function () {
var dataSource = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('country', 'city'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
identify: function (obj) { return obj.country; },
prefetch: "../Data/1.json"
});
function dataSourceS(q, sync) {
dataSource.search(q, sync);
}
$('.typeahead').typeahead( {
minLength: 0,
highlight: true
}, {
name: 'countries',
displayKey: 'country',
source: dataSourceS,
templates: {
empty: [
'<div class="empty">No Matches Found</div>'
].join('n'),
suggestion: function (data){
return '<div>' + data.country + ' – ' + data.city + '</div>'
}
}
}
);
});
这是Json文件
[
{
"country": "Holland",
"city": "Amsterdam"
},
{
"country": "Belgium",
"city": "Brussel"
},
{
"country": "Germany",
"city": "Berlin"
},
{
"country": "France",
"city": "Paris"
}
]
函数很简单。只需要将display参数更新为:
display: function(item){ return item.country+'–'+item.city}
也更新了这里的代码:http://jsfiddle.net/geekowls/agrg3xhj/1/
干杯!