用js完成前端的搜索功能
前言
有的时候,后台并没有提供搜索功能的cgi供前端使用去搜索用户想要查找的内容,这个时候就需要我们前端自己对所有数据进行过滤处理,筛选出与用户搜索内容相匹配的数据进行显示。
方法一:原生js
可以使用原生中的indexOf方法进行数据筛选,代码如下:
//search_data:过滤后的数据
//$scope.all_data:从后台获取到的所有数据
//$scope.filterText:用户输入的搜索内容
//$scope.show_data:显示在页面的数据
var search_data=[];
_.each($scope.all_data,function(ele){
if(ele[0].indexOf($scope.filterText) != -1){
search_data.push(ele);
}
})
$scope.show_data=angular.copy(search_data);
如果我们的数据是数组里面包含json对象的结构,我们就需要使用for…in…的方法对数组里面的json对象进行遍历处理,例如:
//search_data:过滤后的数据
//$scope.filterText:用户输入的搜索内容
//$scope.all_data:从后台获取到的所有数据
//$scope.show_data:显示在页面的数据
var search_data=[];
_.each($scope.all_data,function(ele){
var flag=false;
for(var key in ele){
var ele_key=ele[key];
if(typeof ele_key != 'string'){
ele_key=String(ele_key);
}
if(ele_key.indexOf($scope.filterText) != -1){
flag=true;
break;
}
}
if(flag == true){
search_data.push(ele);
}
})
$scope.show_data=angular.copy(search_data);
筛选出与用户搜索内容相匹配的数据后,如果页面有分页功能,还需要进行分页功能的处理,例如:
//$scope.show_data:与搜索内容相匹配的所有数据
//$scope.dataPage:通过分页功能处理显示在当前页面的数据
// $scope.pagingOption.totalServerItems:总页数
//$scope.pagingOption.currentPage:当前页码
if($scope.pagingOption.currentPage == 1){
$scope.dataPage=angular.copy($scope.show_data.slice(0,$scope.pagingOption.pageSize));
}else{
$scope.pagingOption.currentPage=1;
}
$scope.pagingOption.totalServerItems=$scope.show_data.length;
最终效果如下图所示:
方法二:过滤器filter
可以angular中的过滤器filter,代码如下:
<input type="search" ng-model="input_val" class="form-control" style="width: 980px;" >
<table class="col-xs-24 table table-bordered table-condensed">
<tr>
<th>id</th>
<th>视图名称</th>
<th>创建人</th>
<th>创建时间</th>
<th>更新人</th>
<th>更新时间</th>
<th style="width:160px;">操作</th>
<th style="position:relative;width:70px;">
<button class="btn btn-xs btn-success">全选</button>
</th>
</tr>
/* 过滤出内容中有input_val的数据 */
<tr ng-repeat="col in data | filter: input_val track by $index">
<td>{{col.id}}</td>
<td>{{col.view_name}}</td>
<td>{{col.creator}}</td>
<td>{{col.create_time}}</td>
<td>{{col.updater}}</td>
<td>{{col.update_time}}</td>
<td style="position:relative;width:70px;">
<button class="btn btn-primary btn-xs">选择</button>
<button class="btn btn-primary btn-xs">设置为默认视图</button>
</td>
<td><input type="checkbox" ng-model="col.checked"></td>
</tr>
</table>
最终效果如下图所示:
原始数据:
输入关键词过滤后的数据: