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

AT9*_*T92 2 html javascript checkbox jquery filtering

我正在尝试使用以下代码过滤一些带有复选框的 div:

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

当您选中第一个复选框时,这可以正常工作,但只有在您选择了第一个复选框时,它才会与其他复选框一起过滤。很难解释,但试试 JSFiddle:http : //jsfiddle.net/BY9JL/

我不希望它依赖于选中第一个复选框,有没有办法解决这个问题?

Aru*_*hny 5

尝试

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();
Run Code Online (Sandbox Code Playgroud)

演示:小提琴