我不确定如何正确命名它,但我需要做的在理论上相当简单。我过去曾使用 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 没有此功能,我不反对使用其他东西。
最佳答案
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/
具体来说,请查看自定义模板
关于javascript - typeahead 方法返回相关结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33699410/