jQuery复选框筛选问题:页面加载当前日期筛选不生效,需禁止全取消选中
问题修复方案
核心问题原因
- 通过JS修改复选框选中状态时,不会自动触发绑定的
change事件,因此筛选逻辑不会执行 - 原有代码存在几处语法/选择器不匹配的小bug,也会导致功能异常
具体修改点
- 统一复选框选中状态设置方法:全部使用
prop('checked', true),不要混用attr,设置完成后主动触发change事件 - 修复选择器不匹配问题:HTML中复选框的父容器class是
checkboxes,但JS绑定事件时用的是.filtre-jour,需要统一 - 添加禁止取消选中逻辑:当用户点击已选中的复选框时,阻止默认行为,始终保留至少一个选中项
- 修复HTML语法错误:周日的input标签class属性写法错误,修正为
class="sunday"
完整修改后代码
JS代码
jQuery(function($) { // 日期映射简化冗余判断 const dayMap = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']; const today = new Date(); const todayClass = dayMap[today.getDay()]; // 设置选中并主动触发change事件执行筛选 $(`.${todayClass}`).prop('checked', true).trigger('change'); }) jQuery.expr[":"].CIcontains = jQuery.expr.createPseudo(function(arg) { return function(elem) { return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0; }; }); // 修正选择器为和HTML匹配的.checkboxes input jQuery('.checkboxes input[type="checkbox"]').change(function(e) { const $target = jQuery(this); // 禁止取消已选中的复选框,保证至少有一个选中项 if (!$target.is(':checked')) { e.preventDefault(); $target.prop('checked', true); return; } const thisID = $target.attr('id'); // 其他复选框取消选中,保留单选逻辑 jQuery('.checkboxes input[type="checkbox"]').each(function() { if (jQuery(this).attr('id') != thisID) { jQuery(this).prop('checked', false); } }) const curr_text = $target.data('search-term'); filterResults(curr_text); }); function filterResults(curr_text) { jQuery('.emission-card').hide(); jQuery(`.emission-card:CIcontains("${curr_text}")`).show(); }
HTML代码
<div class="checkboxes"> <input id="#monday" class="monday" data-search-term="monday" type="checkbox"> <label class="inline-checkbox" for="#monday">Lundi</label> <input id="#tuesday" class="tuesday" data-search-term="tuesday" type="checkbox"> <label class="inline-checkbox" for="#tuesday">Mardi</label> <input id="#wednesday" class="wednesday" data-search-term="wednesday" type="checkbox"> <label class="inline-checkbox" for="#wednesday">Mercredi</label> <input id="#thursday" class="thursday" data-search-term="thursday" type="checkbox"> <label class="inline-checkbox" for="#thursday">Jeudi</label> <input id="#friday" class="friday" data-search-term="friday" type="checkbox"> <label class="inline-checkbox" for="#friday">Vendredi</label> <input id="#saturday" class="saturday" data-search-term="saturday" type="checkbox"> <label class="inline-checkbox" for="#saturday">Samedi</label> <!-- 修正class属性写法错误 --> <input id="#sunday" class="sunday" data-search-term="sunday" type="checkbox"> <label class="inline-checkbox" for="#sunday">Dimanche</label> </div>
内容的提问来源于stack exchange,提问作者Gui
相关产品推荐
相关产品推荐

