使用jQuery快速搜索大列表

Sin*_*hus 4 optimization performance search jquery list

我正在使用此代码搜索大约500 li标签.

$(function() {

    $.expr[":"].containsInCaseSensitive = function(el, i, m){
        var search = m[3];
        if (!search) return false;
        return eval("/" + search + "/i").test($(el).text());
    };  

    $('#query').focus().keyup(function(e){
        if(this.value.length > 0){
            $('ul#abbreviations li').hide();
            $('ul#abbreviations li:containsInCaseSensitive(' + this.value + ')').show();
        } else {
            $('ul#abbreviations li').show();    
        }
        if(e.keyCode == 13) {
            $(this).val('');
            $('ul#abbreviations li').show();
        }
    });

});
Run Code Online (Sandbox Code Playgroud)

这是HTML:

<input type="text" id="query" value=""/>
<ul id="abbreviations">
<li>ABC<span>description</span></li>
<li>BCA<span>description</span></li>
<li>ADC<span>description</span></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

这个许多li标签的脚本非常慢.

如何让它更快,如何只搜索li中的ABC文本,而不是搜索span标签(不更改html)?

我知道现有的插件,但我需要一个像这样的小实现.

这是任何感兴趣的人的完成代码

var abbrs = {};

$('ul#abbreviations li').each(function(i){
    abbrs[this.firstChild.nodeValue] = i;
});

$('#query').focus().keyup(function(e){
    if(this.value.length >= 2){
        $('ul#abbreviations li').hide();
        var filterBy = this.value.toUpperCase();
        for (var abbr in abbrs) {
            if (abbr.indexOf(filterBy) !== -1) {
               var li = abbrs[abbr];
               $('ul#abbreviations li:eq('+li+')').show();
            }
        }       
    } else {
        $('ul#abbreviations li').show();    
    }
    if(e.keyCode == 13) {
        $(this).val('');
        $('ul#abbreviations li').show();
    }   
});
Run Code Online (Sandbox Code Playgroud)

Ate*_*ral 7

首先将所有项缓存到对象中:

var abbrs = {};

$("ul#abbreviations li").each(function (i) {
    abbrs[this.firstChild.nodeValue] = this;
});
Run Code Online (Sandbox Code Playgroud)

然后在对象中查找键入的文本:

var li = abbrs[this.value.toUpperCase()];
// show li, hide others
Run Code Online (Sandbox Code Playgroud)

更新:对于部分匹配,您必须遍历集合:

var filterBy = this.value.toUpperCase();

for (var abbr in abbrs) {
    if (abbr.indexOf(filterBy) !== -1) {
        var li = abbrs[abbr];
        // show li
    }
}
Run Code Online (Sandbox Code Playgroud)