我按照这里的说明用血猎犬实现了先行: http://twitter.github.io/typeahead.js/examples/#bloodhound
这是我的HTML:
<div id="remote">
<input class="typeahead" type="text" placeholder="Search for cast and directors">
</div>
这是我的js:
$(document).ready(function() {
var castDirectors = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: '../api/v1/search/people_typeahead',
remote: '../api/v1/search/people_typeahead?q=%QUERY',
dupDetector: function(remoteMatch, localMatch) {
return remoteMatch.value === localMatch.value;
}
});
castDirectors.initialize();
$('#remote .typeahead').typeahead(null, {
name: 'cast-directors',
displayKey: 'value',
source: castDirectors.ttAdapter(),
hint: false,
highlight: true,
templates: {
empty: [
'<div class="empty-message">',
'No matching names',
'</div>'
].join('\n'),
suggestion: Handlebars.compile('<a id="typeahead" href="{{link}}"><p>{{value}}</p></a>')
}
});
});
然而,即使提示设置为false并且突出显示设置为true,我仍然会看到提示并且没有在typeahead中获得突出显示。我应该改变什么?
答案 0 :(得分:16)
尝试放置提示,突出显示并添加minLength:1而不是第一个null,它应如下所示:
$('#remote .typeahead').typeahead(
{
hint: false,
highlight: true,
minLength: 1
},
{
name: 'cast-directors',
displayKey: 'value',
source: castDirectors.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'No matching names',
'</div>'
].join('\n'),
suggestion: Handlebars.compile('<a id="typeahead" href="{{link}}"><p>{{value}}</p></a>')
}
});
答案 1 :(得分:4)
不幸的是,typeahead.js网站上remote example的代码在调用typeahead()
函数时没有使用选项,而复制/粘贴会引导您解决此问题。< / p>
正如prsnca指出的那样,你必须确保在函数的第一个参数中添加这些选项。
$('#remote .typeahead').typeahead(null, {
name: 'best-pictures',
displayKey: 'value',
source: bestPictures.ttAdapter()
});
$('#remote .typeahead').typeahead(
{
hint: false,
highlight: true,
minLength: 1
},
{
name: 'best-pictures',
displayKey: 'value',
source: bestPictures.ttAdapter()
}
);