return 关联结果的预输入方法

typeahead method to return associated results

我不确定这个标题是否合适,但我需要做的在理论上相当简单。我过去曾使用 Twitter 的 typeahead.js 从 pre-defined 列表中查找值。但是,现在我需要 return 一些 other 不同于用户输入的内容,基于他们输入的内容。

我有一个名称和 ID 列表 - 用户会知道名称,但不知道 ID。当他们输入名称时,下拉菜单需要下拉与该名称关联的任何 ID。

typeahead.js 框架是否适用于此?如果是这样,我该怎么做?我在网上找不到任何文档(否则我不知道要搜索什么...)

我的 JSON 将如下所示:

    {
    "1": {
        "name": "John",
        "ID": "1234"
    },
   "2": {
        "name": "Bob",
        "ID": "2345"
    },
   "3": {
        "name": "Matt",
        "ID": "3456"
    },
   "4": {
        "name": "John",
        "ID": "9874"
    }
}

因此,如果用户输入 "John",我希望下拉列表为 return 两个值:

1234
9874

我不反对使用 typeahead.js 以外的东西,如果它没有这个功能。

typeahead.js 仍然是您想要完成的目标的不错选择。

这里有一个 fiddle 和一个工作示例:

https://jsfiddle.net/5fspsx79/

var substringMatcher = function(strs) {
 return function findMatches(q, cb) {
   var matches, substringRegex;
   matches = [];
   substrRegex = new RegExp(q, 'i');
   $.each(strs, function(i, str) {
     if (substrRegex.test(str.name)) {
       matches.push(str);
     }
   });
   cb(matches);
 };
};

var people = [{
    "name": "John",
    "ID": "1234"
},{
    "name": "Bob",
    "ID": "2345"
},{
    "name": "Matt",
    "ID": "3456"
},{
    "name": "John",
    "ID": "9874"
}];

$('#custom-templates .typeahead').typeahead(null, {
  name: 'people',
  display: 'ID',
  source: substringMatcher(people),
  templates: {
    empty: [
      '<div class="empty-message">',
       'unable to find any results.',
       '</div>'
     ].join('\n'),
   suggestion: Handlebars.compile('<div>{{ID}}</div>')
  }
});

您只需添加自定义模板即可。

有一个例子: http://twitter.github.io/typeahead.js/examples/

具体来说,请查看自定义模板