typeahead方法返回相关结果

时间:2015-11-13 18:23:27

标签: javascript jquery json typeahead.js twitter-typeahead

我不确定是否正确地标题,但我需要做的事情在理论上相当简单。我过去曾使用Twitter的typeahead.js来查找预定义列表中的值。但是,现在我需要根据用户键入的内容返回其他的内容。

我有一个名称和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"我希望下拉列表返回两个值:

1234
9874

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

1 个答案:

答案 0 :(得分:2)

typeahead.js仍然是你想要完成的一个很好的选择。

这是一个工作示例的小提琴:

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/

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