全选时如何使用过滤器

时间:2018-10-03 07:32:07

标签: jquery filter

我正在尝试在jQuery中使用.filter。使用此功能,我可以显示特定的数据。但是我的问题是,当我单击all时,它会隐藏所有内容。

$.ajax({
  url: '/api/Item',
  type: 'GET',
  dataType: 'JSOn',
  async: false,
  success: function(res) {
    for (var i = 0; i < res.length; i++) {
      $('#Container').append('' +
        '<div class="col-md-3 col-sm-6 col-xs-12 portfolio-item" data-brand="' + res[i].productBrand + '">' +
        '<div class="portfolio-wrapper">' +
        '<div class="portfolio-thumb">' +
        '<img src="' + res[i].imageIcon + '" alt="" />' +
        '</div>' +
        '<div class="label-text">' +
        '<h3 style="color: #04a185; font-family: VAG Rounded";>' + res[i].productName + '</h3>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '')
    }
  }
})

posts = $('.portfolio-item')
$("#filters li span").click(function() {
  var customType = $(this).attr('data-filter') // category
  posts.hide().filter(function() {
    return $(this).data('brand') === customType;
  }).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="filters" class="clearfix">
  <li><span class="filter" data-filter="all"><h1>All</h1></span></li>
  <li><span class="filter" data-filter="Blooming"><h1>Blooming </h1></span></li>
  <li><span class="filter" data-filter="Sparkling"><h1>Sparkling </h1></span></li>
  <li><span class="filter" data-filter="Sets"><h1>Sets</h1></span></li>
</ul>

1 个答案:

答案 0 :(得分:4)

要执行此操作,您可以检查customTypeall 还是被单击的值。试试这个:

var $posts = $('.portfolio-item')

$("#filters li span").click(function() {
  var customType = $(this).data('filter');
  $posts.hide().filter(function() {
    return customType === 'all' || $(this).data('brand') === customType;
  }).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="filters" class="clearfix">
  <li><span class="filter" data-filter="all"><h1>All</h1></span></li>
  <li><span class="filter" data-filter="Blooming"><h1>Blooming </h1></span></li>
  <li><span class="filter" data-filter="Sparkling"><h1>Sparkling </h1></span></li>
  <li><span class="filter" data-filter="Sets"><h1>Sets</h1></span></li>
</ul>

<div class="portfolio-item" data-brand="Blooming">
   Blooming
</div>
<div class="portfolio-item" data-brand="Sparkling">
   Sparkling
</div>
<div class="portfolio-item" data-brand="Sets">
   Sets
</div>
<div class="portfolio-item" data-brand="Blooming">
   Blooming
</div>