简体   繁体   English

JS / jQuery-使用复选框过滤div

[英]JS / jQuery - Filtering divs with checkboxes

I'm trying to filter some divs with checkboxes using the following code: 我正在尝试使用以下代码过滤带有复选框的一些div:

$("#filterControls :checkbox").click(function() {
  $(".sectionContent").hide();
  $("#filterControls :checkbox:checked").each(function() {
    $("." + $(this).val()).show();
  });
  if($("#filterControls :checkbox").prop('checked') == false){
    $(".sectionContent").show();
  }
});

This works fine when you check the first checkbox, but it only filters with the others when you also have the first checkbox selected. 当您选中第一个复选框时,此方法工作正常,但仅当您同时选中了第一个复选框时,它才会与其他复选框一起过滤。 It's hard to explain but try the JSFiddle: http://jsfiddle.net/BY9JL/ 很难解释,但是尝试一下JSFiddle: http : //jsfiddle.net/BY9JL/

I don't want it to rely on having the first checkbox checked, is there a way around this? 我不希望它依赖于选中第一个复选框,是否有办法解决?

Try 尝试

var sections = $('.sectionContent');
function updateContentVisibility(){
    var checked = $("#filterControls :checkbox:checked");
    if(checked.length){
        sections.hide();
        checked.each(function(){
            $("." + $(this).val()).show();
        });
    } else {
        sections.show();
    }
}

$("#filterControls :checkbox").click(updateContentVisibility);
updateContentVisibility();

Demo: Fiddle 演示: 小提琴

It's because your last if check, it will only check the first checkbox if it is checked or not. 这是因为您的最后一个if复选框仅会检查第一个复选框(如果未选中)。

You could change your last if block to see if there are any checked at all: 您可以更改最后一个if块,以查看是否有任何检查:

if($("#filterControls :checkbox:checked").length == 0){
    $(".sectionContent").show();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM