Typeahead.js 0.10 支持页眉和页脚以及搜索结果的模板。我希望能够获得每个类别的实际结果/建议数量(即忽略限制值)并将其显示在类别名称标题中。
例如 -
结果:
我的模板目前看起来像这样:
{
name: 'Applications',
displayKey: 'value',
source: app.ttAdapter(),
extraVars:Handlebars.registerHelper("numResults",function(){
return ( "HowToGetTheseResults??" );
}),
templates: {
header:Handlebars.compile([
'<h3 class="applications"> Applications ({{numResults}}) results </h3>'
].join('')),
suggestion: Handlebars.compile([
'<p><b>{{value}}</b> </p>'
].join(''))
}
有没有一种简单的方法可以预先输入以返回结果/建议的数量?我确定 typeahead 对象(或猎犬对象?)必须将这些数据存储在某个地方。
最佳答案
您可以定义自己的函数来处理用户输入的查询。
我做了一个样本 fiddle :http://jsfiddle.net/dtengeri/6ApJg/
基本思想是您手动从 Bloodhound 引擎获取建议,并且只将所需数量的结果传递给 typeahead。
// Custom source function in the dataset definition.
source: function (query, cb) {
// Get the data from the Blodhound engine and process it.
nbaTeams.get(query, function (suggestions) {
// Show only the first 3 results.
cb(suggestions.slice(0, 3));
// Set the headers content.
$('#nba-header').text(suggestions.length);
})
},
您必须在标题模板中定义一个 HTML 元素,您将在其中放置结果数量。 (本例中带有 id #nba-header 的跨度。)
templates: {
// Insert an HTML element where you will place the number of results.
header: '<h3 class="league-name">NBA Teams (<span id="nba-header"></span>)</h3>'
}
为了获得所有结果,您应该在 Bloodhound 引擎中设置一个较高的数字作为限制:
var nbaTeams = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: nba(),
limit: Number.MAX_VALUE // Set the limit as high as possible.
});
关于Typeahead.js 0.10.x : how to show number of results per category,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22361286/