我正在编写一个程序,它应该能够根据一些类(class)参数找到大学类(class)。我有一个包含 1360 个对象的巨大 json 对象,每个对象都有大约 20-30 个参数。然而,我只对其中的大约 3-5 个感兴趣。
我想要做的是能够根据类(class)的编号、名称、教师姓名或每门类(class)在其描述中包含的一组关键字来找到类(class)。
无论如何。我试过弄乱 twitters typeahead.js,据我所知,你需要解析一个字符串数组,而且它看起来只需要 1 个数组。有没有一种简单的方法(或另一个 javascript 模块)可以做到这一点?
我当前的对象是:
var courses = [
{ "number": "<5 digits>",
"name": "<course name>",
"teacher": "<teacher name>",
"keywords": "<string of keywords>" }
{ ... }
{ ... }
{ ... }
and so forth..
];
如前所述,它是 1360 个大小的对象。
我想得到类似这样的输出:
但是我希望能够搜索提到的参数(编号、姓名、教师姓名、关键字),并获得与文本字段中输入的任何内容的最佳匹配。
有没有人知道如何实现这一目标?
最佳答案
这很容易,但不是 typeahead.js
.它有 231 Unresolved 问题(当时打字,有些非常严重)并且 年 没有更新。
使用bootstrap3-typeahead反而。它得到维护和更新。在进一步阅读之前先看看文档。您没有提供 JSON,所以我在下面的示例中使用了另一个 JSON。
你所要做的就是定义一个matcher
方法,这里是一个非常简单的不区分大小写的方法,它与 JSON 项中的所有 属性进行比较:
matcher: function(item) {
for (var attr in item) {
if (~item[attr].toString().toLowerCase().indexOf(this.query.toLowerCase())) return true
}
return false
}
您可以使用 displayText
覆盖应在下拉列表中显示的属性/文本(纯粹的例子):
displayText: function(item) {
return item.id + ' ' + item.label + ' ' + item.value
}
如果你想完全覆盖项目的呈现,作为复杂的 HTML,使用 displayText
的组合和 highlighter
其中每个显示字符串都包含字符串化的 JSON:
displayText: function(item) {
return JSON.stringify(item)
},
highlighter: function(item) {
item = JSON.parse(item)
return '<span><h4>'+item.value + '</h4>' + item.id + ' ' + item.label +'</span>'
}
当显示字符串被字符串化时,<input>
必须使用应为所选值的值属性进行更新:
afterSelect: function(item) {
this.$element[0].value = item.value
}
完整示例:
$('#example').typeahead( {
source: json,
matcher: function(item) {
for (var attr in item) {
if (~item[attr].toString().toLowerCase().indexOf(this.query.toLowerCase())) return true
}
return false
},
displayText: function(item) {
return JSON.stringify(item)
},
highlighter: function(item) {
item = JSON.parse(item)
return '<span><h4>'+item.value + '</h4>' + item.id + ' ' + item.label +'</span>'
},
afterSelect: function(item) {
this.$element[0].value = item.value
}
})
关于javascript - Twitter typeahead.js 和一个用于多个匹配的 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36795726/