我有一个建议输入字段来搜索我自己的JSON,以便为英国的可用火车站提供建议。我已经设法通过以下代码完成了这项工作。
$.getScript('//cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.11.1/typeahead.bundle.min.js', function() {
// script is now loaded and executed.
var stations = new Bloodhound({
datumTokenizer: function(datum) {
return Bloodhound.tokenizers.whitespace(datum.simplename);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
sorter: function(a, b) {
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
} else return 0;
},
prefetch: {
url: 'Rails_Feed.json',
cache: false,
transform: function(data) {
return $.map(stations.sorter(data.stations), function(station) {
//debugger;
//console.log(station.id);
if (station.name == 'United Kingdom') {
return {
id: station.id,
name: station.localizedNames[0].extendedValue,
country: station.name,
dest: station.tags.rails['stationCode'],
simplename: station.localizedNames[0].value,
};
}
});
}
}
});
// Instantiate the Typeahead UI
$('#origin-rlp').typeahead({
hint: true,
highlight: true,
minLength: 1
}, {
limit: 10,
name: 'originName',
display: 'name',
value: 'name',
source: stations,
templates: {
empty: [
'<div class="empty-message">',
'no suggessions',
'</div>'
].join('\n'),
suggestion: function(data) {
console.log(data);
return '<div class="address"><span class="icon icon-train"></span> ' + data.name + '</div>';
}
}
}).on('typeahead:selected', function(obj, datum) {
//console.log(datum);
var DestData = new Array();
DestData = $.parseJSON(JSON.stringify(datum));
$('#origin-dest').val(DestData["dest"]);
});
});
我最近学习并使用了typeahead.js时遇到了几个问题。
如果需要,
示例JSON对象如下所示{
"name": "United Kingdom",
"localizedNames": [
{
"value": "London",
"extendedValue": "London,UK"
}
],
"tags": {
"rails": {
"stationCode": "GBLO"
}
},
}