我想到了以下几点:
console.log("1:" + new Date().getTime());
var words = $('.wordlist li');// search take time, check this 20 li in 8ms
console.log("2:" + new Date().getTime());
var filter = $("#filter");
var timer = null;
$("#filter").keyup(function(){
if (timer != null) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function() {
var filterStr = filter.val(), count = 0;
console.log(filterStr);
if(!filterStr){
words.each(function(){
$(this).slideDown('slow');
});
return;
}
var regex = new RegExp(filter, "i");
/*below take time too*/
console.log("3:" + new Date().getTime());
words.each(function(){
var ret = $(this).children('.trans').text().search(regex);
// children faster than find! or we should store text in array like "words" - words = [{this:this, text: text}], cache those text()
// some problem here with search, 'A B C' match with 'aaaa'!
//console.log($(this).children('.trans').text());
console.log(ret);//
if (ret < 0) {
$(this).slideUp('slow');
} else {
$(this).slideDown('slow');
count++;
}
});
console.log("4:" + new Date().getTime());
timer = null;
}, 500);// do not need search each keyup!
});
但最大的问题是你的 10000 里!在 jsfiddle 中,过滤 20 li 需要 20 毫秒!您可以在脚本中手动为您的 li 建立索引(一个大数组而不是 each()、children() 或 finde(),但也很耗时)。
你会在你的服务器中建立一个索引(java-lucence 或任何其他东西)吗?您可以通过 $.ajax 使用关键字(用于搜索)从服务器获取数据(json/xml 格式)。而且,您可以将数据拆分为页面!每个 $.ajax 都可以用“开始”和结束来限制。服务器端解决方案似乎不仅仅是脚本
幻灯片解决方案的伪代码
HTML:
<div id=“searchResult” class="main container" style="overflow-y: auto;overflow-x: hidden;">
<ul class="list-group wordlist">
….
</ul>
</div>
脚本:
//after keyword changed
//query from server, post as a example
$.post("url", {key:"xxx", skip: skipNum, limit: limitNum}, function(response){
data = $.toJSON(response); // if your returning data in JSON
// fade old ul
$("#searchResult").chidren(".wordlist")
.animation({"marginLeft": "-xxxpx"}, "fast", "linear", function() {
//remove old result
//assume $(this) as $("#searchResult").chidren(".wordlist")
$(this).remove();
});
// assume here after removing old result if above was sync
// add new ul foreach result in return data
var newUl = $("<ul>").css({"display", "none", "marging-left": "yyypx"});// hide at first;
for (var i in data) {
$("<li>")
..... // style , text ,chidren node in li
.appendTo(newUl);// append to ul
}
newUl.appendTo($("#searchResult"));
//slide the new ul
newUl.css("display", "block"); //make it display
newUl.animation({"marginLeft":"0px"}.....);
}
另外,你可以用css3做动画