使用jQuery快速搜索大列表 [英] Search through a big list fast with jQuery
本文介绍了使用jQuery快速搜索大列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用此代码搜索大约500个li标签.
I'm using this code to search trough about 500 li tags.
$(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();
}
});
});
这是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>
使用这么多li标签,此脚本非常慢.
This script is very slow with this many li tags.
如何使其更快,如何只搜索li中的ABC文本,而不搜索span标签(不更改html)?
How can I make it faster, and how can I search trough only the ABC text in the li, and not the span tags (without changing the html) ?
我知道现有的插件,但是我需要一个小的实现.
I know about the existing plugins, but I need a small implementation like this.
这是任何有兴趣的人的完整代码
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();
}
});
推荐答案
首先将所有项目缓存到一个对象中:
Cache all items into an object first:
var abbrs = {};
$("ul#abbreviations li").each(function (i) {
abbrs[this.firstChild.nodeValue] = this;
});
然后在对象中查找键入的文本:
Then look for the typed text in your object:
var li = abbrs[this.value.toUpperCase()];
// show li, hide others
更新:对于部分匹配,您必须遍历集合:
Update: For partial matches, you'd have to iterate through the collection:
var filterBy = this.value.toUpperCase();
for (var abbr in abbrs) {
if (abbr.indexOf(filterBy) !== -1) {
var li = abbrs[abbr];
// show li
}
}
这篇关于使用jQuery快速搜索大列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文