我正在尝试用多个复选框进行筛选,我在本例中使用了答案中的代码:Jquery用多个检查框进行筛选它工作得很好,但我需要结果来显示复选框的组合。目前,它只与复选框筛选结果完全匹配。如果对象包含数组中的任意1,而不是数组,我希望它显示所有结果。我不能在我的特定项目中使用同位素,但它会像这个同位素示例:
<a href="http://codepen.io/desandro/pen/btFfG">
编辑:我特别知道这段代码需要修改。此时,如果元素与复选框类别完全匹配,它将循环遍历数组并显示内容。如果任何类别与任何数组变量匹配,我需要它在数组中循环并显示内容:
// create a collection containing all of the filterable elements
var $filteredResults = $('.card');
// loop over the selected filter name -> (array) values pairs
$.each(selectedFilters, function(name, filterValues) {
// filter each .card element
$filteredResults = $filteredResults.filter(function() {
var matched = false;
var currentFilterValues = $(this).data('category').split(' ');
// loop over each category value in the current .card's data-category
$.each(currentFilterValues, function(_, currentFilterValue) {
// if the current category exists in the selected filters array
// set matched to true, and stop looping. as we're ORing in each
// set of filters, we only need to match once
if ($.inArray(currentFilterValue, filterValues) != -1) {
matched = true;
return false;
}
});
// if matched is true the current .card element is returned
return matched;
});
});
在外循环中:
$.each(selectedFilters, function(name, filterValues) {...
您正在对每个选定的过滤器进行迭代,逐步消除那些与过滤器不匹配的过滤器。
$filteredResults = $filteredResults.filter(function() {...
通过的唯一项目满足所有过滤器(即,您正在执行逻辑AND运算)。相反,您需要对.card
项进行一次筛选,若该项的任何$(this).data('category')
值和任何选定的筛选器匹配,则返回true。通过这种方式,您可以执行逻辑"或"运算。