我一直在努力解决过滤存储在数组中的多个数据属性的问题。 我有 2 种不同的过滤器类型(过滤器主题和过滤器内容类型)主题是文章主题,类型是视频或帖子等。 我在文章上使用数据属性来管理这些不同类型的过滤器。
所以从那里我有一个点击事件查看页面上的不同 li 元素,这些元素也分配了数据属性。
<li class="filter-pill" data-category-type="Arts & Creative Industries">Arts & Creative Industries</li>
<li class="filter-pill" data-category-name="Video">Video</li>
我将这些数据存储在一个数组中,然后显示与数组数据匹配的文章。但是,当单击第一个过滤器时,只有单击第二个过滤器(视频或帖子)才会显示任何内容。
我需要能够通过 AND 和 OR 进行过滤,但无法解决这部分问题。
这是我所有代码的小提琴 https://jsfiddle.net/dfwpmLt6/
当您说“我需要能够通过 AND 和 OR 进行过滤”时,我理解您的意思是:
如果这个理解是正确的,我认为跟踪单个数组中选定的过滤器将非常困难。这是因为我们需要单独检查是否选择了任何名称以及任何类型。我的建议是分别存储这些选定的过滤器。例如:
const selectedFilters = {
names: [],
types: []
};
然后我们需要更新更新
selectedFilters
的逻辑:
const changedFilters = {
names: $this.data('category-name'),
types: $this.data('category-type')
};
['names', 'types'].forEach(key => {
if (!changedFilters[key]) { return; }
const value = changedFilters[key];
const index = selectedFilters[key].indexOf(value);
if (index > -1) {
selectedFilters[key] = selectedFilters[key].slice(0, index).concat(selectedFilters[key].slice(index + 1));
} else {
selectedFilters[key].push(value);
}
});
最后,我们循环遍历每个
.article-child
并确定是显示还是隐藏(使用jQuery的.toggle方法)。逻辑将按名称过滤仅当选择了名称并且将按类型过滤仅当选择了类型:
$('.article-child').each(function () {
const $this = $(this);
const categoryName = $this.data('category-name');
const categoryType = $this.data('category-type');
let isVisible = true;
if (selectedFilters.names.length) {
isVisible = isVisible && selectedFilters.names.includes(categoryName);
}
if (selectedFilters.types.length) {
isVisible = isVisible && selectedFilters.types.includes(categoryType);
}
$this.toggle(isVisible);
});
这里是一个小提琴的例子。