我正在创建一个基本过滤器以从列表中删除一些项目。只有 12 个项目,所以 IMO 不足以打扰延迟加载或渲染。只需使用 jQuery 来隐藏项目。
使用select
下拉列表中的数字过滤掉这些项目,一个用于minValue
,一个用于maxValue
。与每个 div 相关的值存储在 div 上的 data-bedrooms
中。
HTML 示例
<div class="property-item" data-bedrooms="7">7 bedrooms</div>
我正在一个下拉菜单的 .change
上触发我的逻辑。然后,我使用 filter()
返回与 minValue
和 maxValue
条件匹配(或不匹配)的项目,并淡化它们进出。
这是一个完整的代码笔,您可以在其中看到所有操作:http://codepen.io/anon/pen/ALdOLW
我发现第一个选择有效(例如,选择 min 4
,您将删除 4
以下的所有内容),但尝试选择最大值和其他内容开始行为不端。
当您选择第二个值时,它会返回之前的所有结果。我需要将两个选择绑定(bind)在一起。
我哪里出错了?
我需要结合 fadeIn
和 fadeOut
来检查 maxValue
和 minValue
return $(this).attr('data-bedrooms') < minValue || > maxValue;
但我知道上面的语法不正确
最佳答案
OP,您的代码似乎总体正常工作,我的猜测是您遇到了一些竞争条件,因为您的代码多次动画。我已经 fork 了您的 codepen,并重新组织了代码,以便您执行两个操作而不是 4 个操作。我还将您的过滤器函数提升到一个单独的函数中。 IMO 通过进行此更改,您可以随着时间的推移提高代码的可读性和可维护性。
// Translating 'min' and 'max' to numbers that we can compare against
// This makes it easier to perform the <= >= checks
if (minValue === 'min-default') {
minValue = 0;
}
if (maxValue === 'max-default') {
maxValue = 1000; // This should probably find the highest value from the available options
}
// Moved this out to its own function that compares the entire range at once
function filterBedroomsRange(index, item) {
var bedrooms = $(item).attr('data-bedrooms');
// Validate against the selected range together to avoid double filter/double animation issues
// The number of bedrooms must be greater than or equal to the min value, and less than, or equal to the maxValue
return bedrooms >= minValue && <= maxValue;
}
// Hide items that don't match the range
properties.find('.property-item').filter(function(index, item) {
// Return the negative of `filterBedroomsRange` to find items to hide
return !filterBedroomsRange(index, item);
}).fadeOut('fast');
// Show items that do match the range
properties.find('.property-item').filter(filterBedroomsRange).fadeIn('fast');
关于javascript - 根据数据属性、最小值和最大值隐藏项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40006277/