【发布时间】:2015-10-16 00:16:15
【问题描述】:
我在 Bootstrap 的 Typeahead 中为建议定义了一个自定义模板,如下所述。但是,当我选择任何建议时,我只会在输入中得到 country 名称。由于我在 displayKey 参数中传递了 country。无论如何我可以在输入中选择 country 和 city 名称(与模板中相同)?
这里是 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"
}
]
【问题讨论】:
标签: javascript jquery typeahead.js typeahead bloodhound