我有一个已知格式的对象数组,它可能看起来像这样:
var items = [{id : 1,
desc : "Funny things",
tags : ["Snippet","Funny"],
title : "Awsome"},
{id : 2,
desc : "Hello World",
tags : ["Fun","Funny"],
title : "What"},
{id : 3,
desc : "True story",
tags : ["Snippet","Cool"],
title : "Is it possible with things?"
}];
我想在我的页面中创建一些搜索功能,以搜索项目内的不同内容,然后以某种方式显示它。有谁知道可以帮助我解决这个问题的插件吗?
我只是尝试使用 jQuery grep 函数并为我的示例想出了这个片段:
var serach = "things"; // Try to get the tags
var obj = $.grep(items, function(n, i){
// Condition one
if(n.desc.indexOf(serach)>=0)
{
return true;
};
// Condition two
if(n.title.indexOf(serach)>=0)
{
return true;
};
// Condition there
var foundTag = false;
for(var i = 0; i<n.tags.length;i++){
if(n.tags[i].indexOf(serach)>=0)
{
foundTag = true;
return true;
};
}
if(foundTag){return true};
return false;
});
它非常简单并且有效。然而,它并没有解决诸如优先级不同的属性之类的问题。如何为功能添加优先级。例如,如果在标题中找到了 serach 表达式,它应该在“匹配”数组中的位置更高。
因此,如果有人有任何好的意见或好的插件,我会发现它很有帮助!
最佳答案
您可以使用 jQuery.each 创建数组并为每个匹配项分配一个权重,然后进行排序。
像这样:
//var serach = "Fun"; Try the tags
var serach = "things"; // Try to get the tags
var obj = [];
$.each(items, function(i, n) {
// Condition one
if(n.desc.indexOf(serach)>=0)
{
obj.push({ weight: 0, value: n });
};
// Condition two
if(n.title.indexOf(serach)>=0)
{
obj.push({ weight: 10, value: n });
};
// Condition there
var foundTag = false;
for(var i = 0; i<n.tags.length;i++){
if(n.tags[i].indexOf(serach)>=0)
{
foundTag = true;
obj.push({ weight: 5, value: n });
};
}
if(foundTag){
obj.push({ weight: 5, value: n });
};
});
obj.sort( function(a, b) {
return a.weight < b.weight;
});
关于javascript - 根据文本查找数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9923625/