【发布时间】:2017-01-05 22:42:55
【问题描述】:
前言:
我正在开发一个功能,允许用户选择数据点来过滤表格。每个表行都有 3 个与之关联的属性,Title、Department 和 Location。
页面上有三个多选过滤器选项,允许用户通过按每个字段选择一个或多个过滤器选项来缩小搜索范围。
当这些选项被选中时,它会触发一个函数来调整表格并仅显示数据与其过滤器匹配的行。
问题:
由于我的函数包含一个独立检查每个过滤器选项的循环,因此它按顺序隐藏/显示行会导致问题。例如,如果它应该显示表中的第一行,因为过滤器告诉它,下一个过滤器说只显示与其过滤器匹配的行,而忽略它之前的行。
我的尝试:
我尝试以隐藏所有行开始的方式构建函数,然后如果表格行的属性包含在我们的过滤器中,它会显示该行。这适用于第一个过滤器,但当它遍历行并命中其他过滤器时,它会在不应该隐藏它们时隐藏它们。
理想的解决方案:
寻找一种方法来清理这个函数,它一次应用过滤器逻辑,而不是按函数调用的顺序。如果我选择Austin 作为我的位置,它将显示具有location=austin 属性的行。如果我随后在过滤器中选择 department,则需要将位置和部门过滤器都应用到表中。
代码示例:
// Filters our user groups based on selections
function filterUserGroups(){
// Define our vars
var locationsFilter = $('[name=in_ugLocationsFilter]').val(),
departmentsFilter = $('[name=in_ugDepartmentsFilter]').val(),
titlesFilter = $('[name=in_ugTitlesFilter]').val(),
tempLocation = '',
tempDepartment = '',
tempTitle = '';
// Loop over our rows and show the data that matches our filters
$('[name=userGroupsRows] tr').hide();
$('[name=userGroupsRows] tr').each(function(){
// Get the current vars of each row
tempLocation = $(this).data('location');
tempDepartment = $(this).data('department');
tempTitle = $(this).data('title');
// Do we have any filter options selected?
if(locationsFilter || departmentsFilter || titlesFilter){
// If the location is in our filter, show row
if(jQuery.inArray(tempLocation, locationsFilter) != -1) {
$(this).show();
}
// If the departmentis in our filter, show row
if(jQuery.inArray(tempDepartment, departmentsFilter) != -1) {
$(this).show();
}
// If the title is in our filter, show row
if(jQuery.inArray(tempTitle, titlesFilter) != -1) {
$(this).show();
}
}
})
}
【问题讨论】:
-
我猜您所拥有的实际上是过滤器之间的“或”,而您想要的是“和”?对吗?
-
@Ouroborus 是的,听起来不错 - 想不出一个简单的方法来解释这一点。
-
您考虑过使用datatables.net 吗?
标签: javascript jquery html filter