首页 > 解决方案 > jQuery复选框列表显示包含数据的项目

问题描述

我正在尝试使用复选框列表作为过滤器来显示和隐藏具有特定数据属性值的项目。由于某种原因,我无法弄清楚或找到一个例子。当然应该有些什么容易。我或多或少想显示与复选框的值匹配的所有元素,甚至是多选项目。所以在我下面的例子中。我想要显示任何带有绿色的东西,然后显示任何带有橙色的东西。但我也展示了任何元素上带有绿色和橙色的东西。

非常感谢任何帮助。

例子:

我的元素:

 <div id="myFilters">
<label><input type="checkbox" value="red" name="colorCheckbox">red</label>

<label><input type="checkbox" value="orange" name="colorCheckbox">orange</label>
<label><input type="checkbox" value="green" name="colorCheckbox">green</label>
  </div>

 <div data-type="red green"></div>
 <div data-type="red orange green"></div>
 <div data-type="red orange"></div>

我的 jQuery

 $('input[type="checkbox"]').click(function(){

   var inputValue = $(this).attr("value");
    $("div[data-type=" + inputValue).show();
     $('div:not([data-type=' + inputValue).hide();
  });

我有一个 JSFiddle 和我当前的代码。

https://jsfiddle.net/azm58kxf/1/

标签: jqueryhtml

解决方案


单击时,从每个选中的复选框值构造一个数组。然后,遍历data-typediv 并检查它们type includes是否在数组中的任何字符串 - 如果是,则显示 div,否则隐藏它:

const $checkboxes = $('#myFilters input[type="checkbox"]')
$checkboxes.click(function() {
  const substringsToShow = $checkboxes.filter(':checked')
    .map((_, elm) => elm.value)
    .get();
  $('.datas').each(function() {
    const $this = $(this);
    const type = $this.data('type');
    if (substringsToShow.some(show => type.includes(show))) {
      $this.show();
    } else {
      $this.hide();
    }
  });
});
.datas {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myFilters">
  <label><input type="checkbox" value="red" name="colorCheckbox">red</label>

  <label><input type="checkbox" value="orange" name="colorCheckbox">orange</label>
  <label><input type="checkbox" value="green" name="colorCheckbox">green</label>
</div>

<div class="datas" data-type="red green">redgreen</div>
<div class="datas" data-type="red orange green">redorangegreen</div>
<div class="datas" data-type="red orange">redorange</div>


推荐阅读