【问题标题】:Twitter typeahead default suggestions: how to get the first suggestions in the prefetched array?Twitter typeahead 默认建议:如何获取预取数组中的第一个建议?
【发布时间】:2015-04-26 09:10:47
【问题描述】:

我正在使用 Twitter Typeahead,我想在输入框获得焦点时向用户提供一些值,然后再输入任何内容。

在默认建议下的examples page 上有一个示例:

var nflTeams = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  identify: function(obj) { return obj.team; },
  prefetch: '../data/nfl.json'
});

function nflTeamsWithDefaults(q, sync) {
  if (q === '') {
    sync(nflTeams.get('Detroit Lions', 'Green Bay Packers', 'Chicago Bears'));
  }

  else {
    nflTeams.search(q, sync);
  }
}

$('#default-suggestions .typeahead').typeahead({
  minLength: 0,
  highlight: true
},
{
  name: 'nfl-teams',
  display: 'team',
  source: nflTeamsWithDefaults
});

但是在示例中,他们硬编码了他们想要建议的值:

      sync(nflTeams.get('Detroit Lions', 'Green Bay Packers', 'Chicago Bears'));

在我的例子中,我使用带有预取的 Bloodhound,我想建议预取返回的前几个选项。

编辑: 我想展示的是服务器返回的前几项。服务器将负责显示它们的顺序。所以在上面的例子中,如果 data/nfl.json 包含:

[
{ "team": "San Francisco 49ers" },
{ "team": "Chicago Bears" },
{ "team": "Cincinnati Bengals" },
{ "team": "Buffalo Bills" },
{ "team": "Denver Broncos" },
{ "team": "Cleveland Browns" },
...

我只想展示第一支球队是什么。显示的团队数量可以是一个参数。

我该怎么做?

【问题讨论】:

  • 当你说first few options时,你将如何确定有多少和几个?你能说得更具体些吗?
  • 服务器正在向我发送一个数组。我可以使用数组中的第 n 个项目(比如 6 个或 10 个第一个项目)。由服务器决定排序。

标签: javascript twitter-typeahead


【解决方案1】:

例如,您希望默认显示 2 个第一个项目

function nflTeamsWithDefaults(q, sync) {
    if (q === '') {
        sync(nflTeams.all().slice(0, 2)); // slice(start,end)
    }
    else {
        nflTeams.search(q, sync);
    }
}

【讨论】:

  • 问题要求 hep 与 BloodHound 数据源。所以没有`来源:nflTeamsWithDefaults`(在我的理解中)。应该是source: nflTeams.ttAdapter()。而且没有办法用nflTeamsWithDefaults查询。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多