`
xangqun
  • 浏览: 80214 次
  • 性别: Icon_minigender_1
  • 来自: 江西
社区版块
存档分类
最新评论

jquery 实现过滤器(转载)

阅读更多

本文转载自:http://abruzzi.iteye.com/blog/519288

公司产品的一个新功能中涉及到一个过滤器:通过关键字快速的对结果集进行过滤,获得比较少的结果,方便用户选择。在网上找了找,有很多jQuery的插件,要么就是auto complete, 要么就是没有高亮的quick search,都不是很适合我们的场景,于是就自己实现了一个。用起来倒是还过得去,呵呵。

 

效果图:

对一个List进行过滤(假设List很长,隐藏掉其他无关的项,例子里是美国的50个州,只搜索有"na"字符串的):



 对一个table进行过滤(table的其他列不隐藏,只是高亮搜索到的):



 当然,可以将其结合在一起,那样一个页面中可以有多个过滤器:



其实,实现起来,代码量很小,这里先大概说一下原理:

将搜索框中的字符收集起来,作为关键字,当搜索框中的内容发生变化时(keyup事件 ),做一次过滤,将匹配的内容高亮起来(如果有上一次的内容,需要做一个清空处理,比如第一次键入的是a,第二次键入的是al,则在al键入之后要将之前高亮的a恢复正常)。

 

主要用到了javascript的正则表达式,还有就是jQuery的强大的选择器,下边看看具体代码(demo附后下载):

Js代码 复制代码
  1. /**  
  2.  * this is the do-filter function, used to filter the contents  
  3.  *  
  4.  * @params contents contents is the container of all items which  
  5.  *         need to filter, it's a jQuery object.  
  6.  *  
  7.  * @params keyword keyword is a string, used to be the condition  
  8.  *         of the filter  
  9.  *  
  10.  * @params options options is a JSON object, may contains:  
  11.  *         {  
  12.  *          keep : true or false to detemine whether keep the container or not,  
  13.  *          reopts : regular expression options, may be "g", "i", or "gi"   
  14.  *         }  
  15.  *  
  16.  */  
  17. function doFilter(contents, keyword, options){   
  18.     var filterOptions = jQuery.extend({   
  19.         keep : false,    
  20.         reopts : "gi",   
  21.         highlight : "#caff70"  
  22.     }, options);   
  23.        
  24.     if(!filterOptions.keep){contents.hide();}   
  25.     contents.each(function(){   
  26.         var text = $(this).text();   
  27.         var pattern = new RegExp(keyword, filterOptions.reopts);   
  28.         if(pattern.test(text)){   
  29.             var item = text.replace(pattern, function(t){   
  30.                 return "<span style=\"background:"+filterOptions.highlight+"\">"+t+"</span>";   
  31.             });            
  32.             $(this).html(item).show();   
  33.         }else{//clear search result of last   
  34.             $(this).find("span").each(function(){   
  35.                 $(this).replaceWith($(this).text());   
  36.             })   
  37.         }   
  38.     });   
  39. }  
/**
 * this is the do-filter function, used to filter the contents
 *
 * @params contents contents is the container of all items which
 *         need to filter, it's a jQuery object.
 *
 * @params keyword keyword is a string, used to be the condition
 *         of the filter
 *
 * @params options options is a JSON object, may contains:
 *         {
 *          keep : true or false to detemine whether keep the container or not,
 *          reopts : regular expression options, may be "g", "i", or "gi" 
 *         }
 *
 */
function doFilter(contents, keyword, options){
	var filterOptions = jQuery.extend({
		keep : false, 
		reopts : "gi",
		highlight : "#caff70"
	}, options);
	
	if(!filterOptions.keep){contents.hide();}
	contents.each(function(){
		var text = $(this).text();
		var pattern = new RegExp(keyword, filterOptions.reopts);
		if(pattern.test(text)){
			var item = text.replace(pattern, function(t){
				return "<span style=\"background:"+filterOptions.highlight+"\">"+t+"</span>";
			});			
			$(this).html(item).show();
		}else{//clear search result of last
			$(this).find("span").each(function(){
				$(this).replaceWith($(this).text());
			})
		}
	});
}

 

主要的选项可以定制,如过滤的规则(正则表达式的选项,全局? 忽略大小写?),高亮色彩的配置,以及是否保留源数据集的可视性。比如,List这种控件,一般是较长的时候进行一下搜索过滤,不需要保持源数据集,而table这种控件,则一般需要保持控件的结构,需要保持源数据集。

 

用法如下:

Js代码 复制代码
  1. var sb = $("#searchBox").val("").focus();   
  2.   
  3. var resultSet = $("div#contentPanel div.item");//used for restore   
  4. sb.keyup(function(){   
  5.     var str = $(this).val();   
  6.     doFilter(resultSet, str);   
  7. });  
	var sb = $("#searchBox").val("").focus();
	
	var resultSet = $("div#contentPanel div.item");//used for restore
	sb.keyup(function(){
		var str = $(this).val();
		doFilter(resultSet, str);
	});

首先,将用作填写关键字的input获取到,然后取得数据集的list,包装成jQuery对象,将doFilter绑定到input的keyup事件上即可。

 

好了,大概也说明白了,自己也加深一下记忆,这一向在实现一套基于web的控件,基本的模型已经差不多了,过两天整理整理分享一下,呵呵。

 

 

按照bluemeteor的建议,将highlight参数改成更为通用的css class,用户同时可以将字体信息等传入作为highlight。总体效果如前文中的截图。代码更新如下:

Js代码 复制代码
  1. function doFilter(contents, keyword, options){   
  2.     var filterOptions = jQuery.extend({   
  3.         keep : false,    
  4.         reopts : "gi",   
  5.         highlight : "highlight"  
  6.     }, options);   
  7.        
  8.     if(!filterOptions.keep){contents.hide();}   
  9.     contents.each(function(){   
  10.         var text = $(this).text();   
  11.         var pattern = new RegExp(keyword, filterOptions.reopts);   
  12.         if(pattern.test(text)){   
  13.             var item = text.replace(pattern, function(t){   
  14.                 return "<span class=\""+filterOptions.highlight+"\">"+t+"</span>";   
  15.             });            
  16.             $(this).html(item).show();   
  17.         }else{//clear search result of last   
  18.             $(this).find("span."+filterOptions.highlight).each(function(){   
  19.                 $(this).replaceWith($(this).text());   
  20.             })   
  21.         }   
  22.     });   
  23. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics