<div> <label> <input type="checkbox" id="not-effective" onclick="filterItems()">未生效 </label> <label> <input type="checkbox" id="effective" onclick="filterItems()">已生效 </label> </div> <div id="content"> <div class="item" data-status="not-effective">未生效的内容1</div> <div class="item" data-status="not-effective">未生效的内容2</div> <div class="item" data-status="effective">已生效的内容1</div> <div class="item" data-status="effective">已生效的内容2</div> <!-- 可以添加更多内容 --> </div>
原生js实现方法
function filterItems() { const notEffectiveCheckbox = document.getElementById('not-effective'); const effectiveCheckbox = document.getElementById('effective'); const items = document.querySelectorAll('#content .item'); items.forEach(item => { const status = item.getAttribute('data-status'); if ((notEffectiveCheckbox.checked && status === 'not-effective') || (effectiveCheckbox.checked && status === 'effective') || (notEffectiveCheckbox.checked && effectiveCheckbox.checked)) { item.style.display = 'block'; } else { item.style.display = 'none'; } }); } // 初始化筛选功能,页面加载时执行一次,确保默认状态正确 window.onload = filterItems;
jquery实现方法
$(document).ready(function() { // 定义一个函数来处理筛选逻辑 function filterItems() { var showNotEffective = $('#not-effective').is(':checked'); var showEffective = $('#effective').is(':checked'); $('#content .item').each(function() { var $item = $(this); var isNotEffective = $item.data('status') === 'not-effective'; var isEffective = $item.data('status') === 'effective'; // 根据复选框的状态决定是否显示内容项 if ((showNotEffective && isNotEffective) || (showEffective && isEffective) || (showNotEffective && showEffective)) { $item.show(); } else { $item.hide(); } }); } // 绑定复选框的change事件 $('#not-effective, #effective').on('change', filterItems); // 初始调用筛选函数以应用初始状态(可选,但在这个例子中由于初始隐藏了所有项,所以这一步是必要的) filterItems(); });
标签:jquery,status,checked,effective,复选框,item,&&,筛选 From: https://www.cnblogs.com/srqsl/p/18497679