默认情况下,twitter typeahead.js仅返回在字符串开头匹配的元素,例如:
来源:['type','typeahead','ahead']
查询:'type'
返回:'type'和'typeahead'
-
查询:'提前'
返回:'提前'
我希望它返回'提前'和'打字'
我的代码:
var clients = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.value); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
prefetch: {
url: '/clients.json',
filter: function(list) {
return $.map(list, function(value) { return { name: value }; });
}
}
});
clients.initialize();
$('.client').typeahead(null, {
displayKey: 'value',
source: clients.ttAdapter(),
minLength: 1,
});
已经有一个问题,但我不明白答案。
答案 0 :(得分:40)
我找到了一个解决方案......问题是我已经习惯了bootstrap2 typeahead,因为我不理解datumTokenizer
这个问题。如果其他人觉得难以理解,我会在下面做一些描述:
queryTokenizer:你要查询的单词数组,如果查询'test abcd',它会将字符串转换为['test','abcd'],然后查找与这两个单词的匹配。
datumTokenizer:将与queryTokenizer匹配的单词数组。 JSON中的每个项目都有一组要匹配的单词。
所以如果你有一个来源:
['测试'','测试不好']
并查询'est'。你需要让datumTokenizer返回一个包含'est'的数组,如:
第一项['good','test','ood','od','test','est','st']
第二项['bad','ad','test','est','st']
贝娄是我写的代码,我不知道它是否是最佳选择,但我认为它无论如何都会有所帮助:
new Bloodhound({
datumTokenizer: function(d) {
var test = Bloodhound.tokenizers.whitespace(d.value);
$.each(test,function(k,v){
i = 0;
while( (i+1) < v.length ){
test.push(v.substr(i,v.length));
i++;
}
})
return test;
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
prefetch: {
url: '/lista.json',
ttl: 10000
}
});