jquery - 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 和我当前的代码。
解决方案
单击时,从每个选中的复选框值构造一个数组。然后,遍历data-type
div 并检查它们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>
推荐阅读
- c# - 无法从程序集中加载类型
- c - 如何在 C 中使用此代码使用插入排序对列表进行排序?
- spring-boot - Spring Boot 和 OAuth2 maven 依赖项入门
- r - R qdap 搜索排除语法
- mixpanel - 我应该在我的网站上(以及在哪里)添加什么代码来使用 segment.com 在我的网站上跟踪事件/识别用户?
- time-complexity - 关于计算时间复杂度的问题
- java - 将长字符串解析为 LocalDate 变量
- ios - 如何从递归视图控制器返回根视图控制器(四)
- angular - 服务组件之间的交互
- java - 使用java创建定时循环进度条