javascript - 根据数据属性、最小值和最大值隐藏项目

标签 javascript jquery

我正在创建一个基本过滤器以从列表中删除一些项目。只有 12 个项目,所以 IMO 不足以打扰延迟加载或渲染。只需使用 jQuery 来隐藏项目。

使用select下拉列表中的数字过滤掉这些项目,一个用于minValue,一个用于maxValue。与每个 div 相关的值存储在 div 上的 data-bedrooms 中。

HTML 示例

<div class="property-item" data-bedrooms="7">7 bedrooms</div>

我正在一个下拉菜单的 .change 上触发我的逻辑。然后,我使用 filter() 返回与 minValuemaxValue 条件匹配(或不匹配)的项目,并淡化它们进出。

这是一个完整的代码笔,您可以在其中看到所有操作:http://codepen.io/anon/pen/ALdOLW

我发现第一个选择有效(例如,选择 min 4 ,您将删除 4 以下的所有内容),但尝试选择最大值和其他内容开始行为不端。

当您选择第二个值时,它会返回之前的所有结果。我需要将两个选择绑定(bind)在一起。

我哪里出错了?

我需要结合 fadeInfadeOut 来检查 maxValueminValue

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');

代码笔:http://codepen.io/anon/pen/VKdPNB

关于javascript - 根据数据属性、最小值和最大值隐藏项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40006277/

相关文章:

java - GWT 无限滚动并丢弃列表开始结果

javascript - 删除 highcharts 数据标签上的阴影/背景发光?

javascript - 删除数组中指定数量的元素

javascript - 单击 CSS/JQuery 动画 DIV

javascript - AngularJS ng-repeat Post Value 未使用 id 作为键获得正确的模式

javascript - JavaScript 类中的 "SyntaxError: Unexpected identifier"

javascript - 两个数组中最接近值的集合

javascript - $.ajax 无法正常运行 - 返回 index.html

javascript - 调用两次时 jQuery offset(coords) 的行为不一致

javascript - 在窗口大小更改时更改侧导航栏