以下是 jQuery过滤器插件fastLiveFilter js代码 的示例演示效果:
部分效果截图:
HTML代码(index.html):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery过滤器插件fastLiveFilter</title>
<script src="jquery.js"></script>
<script src="jquery.fastLiveFilter.js"></script>
<script>
$(function() {
$('#search_input').fastLiveFilter('#search_list');
});
</script>
<style type="text/css">
body { margin: 0px; background-color: #F6F6F6; }
.jq22{ width: 600px; height: 500px; margin-left: auto; margin-right: auto; background-color: #FFFFFF; padding: 10px; }
</style>
</head>
<body>
<div class="jq22">
<input id="search_input" placeholder="输入文字开始筛选">
<ul id="search_list">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>One</li>
<li>awo</li>
<li>bhree</li>
<li>cne</li>
<li>dwo</li>
<li>ehree</li>
<li>fne</li>
<li>gwo</li>
<li>hhree</li>
<li>ihree</li>
</ul>
</div>
</body>
</html>
JS代码(jquery.fastLiveFilter.js):
/** * fastLiveFilter jQuery plugin 1.0.3 * * Copyright (c) 2011,Anthony Bush * License:<http://www.opensource.org/licenses/bsd-license.php> * Project Website:http://anthonybush.com/projects/jquery_fast_live_filter/ **/
jQuery.fn.fastLiveFilter = function(list,options){
// Options:input,list,timeout,callbackoptions = options ||{
}
;
list = jQuery(list);
var input = this;
var lastFilter = '';
var timeout = options.timeout || 0;
var callback = options.callback || function(){
}
;
var keyTimeout;
// NOTE:because we cache lis & len here,users would need to re-init the plugin// if they modify the list in the DOM later. This doesn't give us that much speed// boost,so perhaps it's not worth putting it here.var lis = list.children();
var len = lis.length;
var oldDisplay = len > 0 ? lis[0].style.display:"block";
callback(len);
// do a one-time callback on initialization to make sure everything's in syncinput.change(function(){
// var startTime = new Date().getTime();
var filter = input.val().toLowerCase();
var li,innerText;
var numShown = 0;
for (var i = 0;
i < len;
i++){
li = lis[i];
innerText = !options.selector ?(li.textContent || li.innerText || ""):$(li).find(options.selector).text();
if (innerText.toLowerCase().indexOf(filter) >= 0){
if (li.style.display == "none"){
li.style.display = oldDisplay;
}
numShown++;
}
else{
if (li.style.display != "none"){
li.style.display = "none";
}
}
}
callback(numShown);
// var endTime = new Date().getTime();
// console.log('Search for ' + filter + ' took:' + (endTime - startTime) + ' (' + numShown + ' results)');
return false;
}
).keydown(function(){
clearTimeout(keyTimeout);
keyTimeout = setTimeout(function(){
if( input.val() === lastFilter ) return;
lastFilter = input.val();
input.change();
}
,timeout);
}
);
return this;
// maintain jQuery chainability}