我无法让 typeahead.js 仅返回与输入查询匹配的结果。例如,如果我在公司搜索栏中输入“Facebook”,它将返回所有公司(“Yahoo”、“Google”等),即使其中大多数与查询不匹配。我没有对数据进行任何服务器端处理。我的 datumTokenizer 函数应该处理这个过滤吗?
另外,我注意到每次修改查询时,它都会为每个数据输入 filter() 函数。因此,当我将查询从“G”更改为“Go”时,filter: function (companies_list) 中的 console.log() 语句将打印 3000 次。
这是我的代码:
var companies = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.name);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/json/company_list.json',
filter: function (companies_list) {
// Map the remote source JSON array to a JavaScript object array
return $.map(companies_list, function (company) {
console.log('mapping')
return {
name: company.name
};
});
}
}
});
// Initialize the Bloodhound suggestion engine
var promise = companies.initialize();
promise.done(function() {console.log('Bloodhound initialized!')});
// passing in `null` for the `options` arguments will result in the default
// options being used
$('#form-company').typeahead(null, {
name: 'companies',
displayKey: 'name',
// `ttAdapter` wraps the suggestion engine in an adapter that
// is compatible with the typeahead jQuery plugin
source: companies.ttAdapter()
});
还有一个我的网址返回的例子:
[{"name": "Yahoo"}, {"name": "Sanchai Technologies "}, {"name": "Oliver Wyman"}, {"name": "University of Oregon"}, ...]
我正在使用远程,因为预取绝对不适合我。它只给了我建议[object Object],这没有任何意义。我想在初始化时使用预取/远程加载整个 .json 文件,而不是向服务器发出任何进一步的请求。所以我认为预取是我更好的选择(小文件,77kB),但它根本不起作用。
非常感谢您的帮助!