默认情况下,推特typeahead.js只返回字符串开头匹配的元素,例如:
来源:'type','typeahead','ahead‘
查询:'type‘
返回:'type‘和'typeahead’
--
查询:'ahead‘
返回:'ahead‘
我想让它返回'ahead‘和'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,
});
已经有一个关于它的问题了,但我不明白答案。
发布于 2014-02-27 22:59:31
我找到了一个解决方案。问题是我太习惯于bootstrap2 typeahead了,以至于我不理解datumTokenizer
的事情。如果其他人觉得很难理解,我会在下面做一些描述:
queryTokenizer:您正在查询的单词数组,如果您查询“test abcd”,它会将字符串转换为“test”和“abcd”,然后查找与这两个单词匹配的内容。
datumTokenizer :将与queryTokenizer匹配的单词数组。JSON中的每一项都将有一组要匹配的单词。
所以如果你有一个来源:
‘好测试’,‘坏测试’
并查询“est”。您需要让datumTokenizer返回一个包含'est‘的数组,如下所示:
‘'good','test','od',’od‘,'test','est','st’代表第一项
‘'bad','ad','test','est','st’代表第二项
Bellow是我写的代码,我不知道这是不是最适合它的东西,但我认为它会有帮助的:
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
}
});
https://stackoverflow.com/questions/22059933
复制相似问题