我很难找到typeahead.js来返回/渲染我页面上的所有结果。这是我的代码:
var places = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/api/place/?country={{ country.id }}&name=%QUERY'
, transform: function (data) {
return data.response;
}
, wildcard: '%QUERY'
}
});
var selected = false;
$('.typeahead-place').typeahead({
hint: true,
highlight: true,
minLength: 2
},
{
name: 'places',
displayKey: function (obj) {
if (obj.url != null && obj.url.length && (obj.street == null || obj.street.length == 0)) {
return obj.name + " (Online store)";
}
return obj.name + " (" + obj.street + ", " + obj.city + ", " + obj.postcode + ")";
},
source: places
});
Punn
的示例查询让我从服务器返回JSON:
{
"response": [
{
"id": "4",
"name": "Punnitse ja Säästä 2",
"street": "Simonkenttä, Simonkatu 9",
"city": "Helsinki",
"postcode": "00100",
"url": "http://www.punnitse.fi/"
},
{
"id": "12",
"name": "Punnitse ja Säästä 3",
"street": "Simonkenttä, Simonkatu 9",
"city": "Helsinki",
"postcode": "00100",
"url": "http://www.punnitse.fi/"
},
{
"id": "13",
"name": "Punnitse ja Säästä 4",
"street": "Simonkenttä, Simonkatu 9",
"city": "Helsinki",
"postcode": "00100",
"url": "http://www.punnitse.fi/"
},
{
"id": "9",
"name": "Punnitse ja Säästä Kamppi",
"street": "Simonkenttä, Simonkatu 9",
"city": "Helsinki",
"postcode": "00100",
"url": "http://www.punnitse.fi/"
}
]
}
现在这样呈现:
答案 0 :(得分:16)
这似乎是typeahead.js
新版本的well-known bug。为了使您的代码正常工作,您宁愿切换到版本 0.10.5 或更低版本,并稍微转换您的代码:
var places = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/api/place/?country={{ country.id }}&name=%QUERY',
wildcard: '%QUERY',
filter: function(data) { // <-- should use `filter`
return data.response;
}
}
});
places.initialize(); // <-- initialise suggestion
$('.typeahead-place').typeahead({
hint: true,
highlight: true,
minLength: 2
}, {
name: 'places',
source: places.ttAdapter(), // <-- get adapter as a source
displayKey: function(obj) {
// ...
}
});
DEMO: https://jsfiddle.net/uszcp6j3/
或者,如果您想坚持使用最新版本,可以将前一段时间发布的the following patch应用于typeahead.js
的源代码。
答案 1 :(得分:6)
我刚刚在这里找到了答案:https://github.com/twitter/typeahead.js/issues/1232提供的louy:
...
$('.typeahead-place').typeahead({
hint: true,
highlight: true,
minLength: 2,
limit: Infinity
},
...
...也就是说,您需要设置Javascript全局 Infinity 属性的限制。这完全有效!
那就是说,他们还没有修补代码是犯罪行为 - 这个错误已经为年所知。