如何根据一些复选框向'data-attribute'添加多个值并使用jQuery过滤它们?

时间:2018-02-02 05:35:09

标签: jquery

我希望能够使用多个数据属性过滤结果。请查看示例代码。当你选择'孟菲斯'或'卡多娃'时,它应该显示'孟菲斯和科尔多瓦'。目前这不起作用。我该怎么做呢?

以下是我的HTML:

$('.filter').change(function() {
  //on each click, refresh visible / hidden for each item
  $('li.result').each(function(i, item) {
    var city = $(this).data('city');
    var visible = $('input.filter[data-city="' + city + '"]:checked').length > 0;
    visible ? $(this).show() : $(this).hide();
  });

  //if no checkboxes are checked, show everything
  if ($('input.filter:checked').length === 0) $('li.result').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  <input class="filter" data-city="Memphis" type="checkbox" /> memphis
  <input class="filter" data-city="Cordova" type="checkbox" /> cordova
  <input class="filter" data-city="Bartlett" type="checkbox" /> bartlett
</p>

<ul>
  <li class="result" data-city="Memphis,Cordova">Memphis and Cordova</li>
  <li class="result" data-city="Memphis">Memphis</li>
  <li class="result" data-city="Cordova">Cordova</li>
  <li class="result" data-city="Bartlett">Bartlett</li>
</ul>

1 个答案:

答案 0 :(得分:0)

这就是诀窍:

$('.filter').change(function() {
  //reset all classes (remove show class)
  $('li.result').removeClass('show');
  //loop over the filters
  $('.filter:checked').each(function() {
    //store the city of the filter in a string called 'city'
    var city = $(this).data('city');
    $('li.result').each(function() {
      //check if the data attribute of the result contains the city string
      //if it matches this filter, add the class 'show' to this result
      $('.result[data-city*="' + city + '"]').addClass('show');
    });
  });
  if ($('input.filter:checked').length === 0) {
    //if no checkboxes are checked, show everything
    $('li.result').show();
  }
  else {
    //else hide everything
    $('li.result').hide();
    //and show only items that match (with class 'show')
    $('li.result.show').show();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  <input class="filter" data-city="Memphis" type="checkbox" /> memphis
  <input class="filter" data-city="Cordova" type="checkbox" /> cordova
  <input class="filter" data-city="Bartlett" type="checkbox" /> bartlett
</p>
    
<ul>
  <li class="result" data-city="Memphis,Cordova">Memphis and Cordova</li>
  <li class="result" data-city="Memphis">Memphis</li>
  <li class="result" data-city="Cordova">Cordova</li>
  <li class="result" data-city="Bartlett">Bartlett</li>
</ul>