javascript - 根据文本查找数组中的项目

标签 javascript jquery jquery-plugins

我有一个已知格式的对象数组,它可能看起来像这样:

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;
});

http://jsfiddle.net/Az2rA/1/

它非常简单并且有效。然而,它并没有解决诸如优先级不同的属性之类的问题。如何为功能添加优先级。例如,如果在标题中找到了 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/

相关文章:

javascript - 使用点击事件 javascript 创建简单的星级评定

javascript - 我如何关闭这部分 CK 编辑器?

javascript - 更改父级的兄弟类

javascript - Angular 中具有 ngModel 和多个字段的自定义组件

jquery - 想要测试 JQuery 中背景颜色的名称

jquery - 取消 jquery sortable 中的 mouseup 以防止 lightbox 响应

jquery - 如何将多个元素放在 div 的第二行

javascript - jQuery .change() 未在选择时触发 - 来自 api.jquery.com 的示例

javascript - 使用 Javascript 从 CSS 类创建 HTML 属性的最佳方法

sql - rails : Using jquery tokeninput (railscast #258) to create new entries