无法将复选框与此查找功能组合在一起

时间:2013-03-27 06:52:59

标签: jquery find show-hide

我无法使此find函数与复选框一起正常工作。我无法选择任何复选框,因此被告知删除语句return false;我不确定这是否是原因,但语句if (attrColor == 'All'){...}不再有效。

如何修改此功能以便它可以使用复选框,包括显示所有选中的内容?

我在这里发布了一个简单的函数示例:http://jsfiddle.net/chayacooper/WZpMh/92/

$(document).ready(function () {
    var selected = [];
    $('#attributes-Colors *').click(function () {
        var attrColor = $(this).data('color');
        var $this = $(this);
        if ($this.parent().hasClass("active")) {
            $this.parent().removeClass("active");
            selected.splice(selected.indexOf(attrColor),1);
        }
        else {
            $this.parent().addClass("active");
            selected.push(attrColor);
        }
        if (attrColor == 'All') {
            $('#content').find('*').show();
        } else {
        $("#content").find("*").hide();
        $.each(selected, function(index,item) {
            $('#content').find('[data-color *="' + item + '"]').show();
        });
        }
        // Removed this to allow checkboxes to accept input
        //return false;
    });
});   

1 个答案:

答案 0 :(得分:0)

仅定位复选框,而不是像星号选择器那样的所有元素,并使用“更改”事件作为复选框。

然后获取变量lis中的所有li元素,并同时隐藏所有这些元素。

将所有选中的复选框颜色映射到包含$.map的数组。

isAll检查该数组的值是否为“全部”以查看是否选中了该复选框,如果是,或者未选中复选框,即长度为空,则显示全部li's,否则使用$.each对选中的复选框中的颜色进行迭代,并显示与所选颜色匹配的任何lis。

$(document).ready(function () {
    $('#attributes-Colors input[type="checkbox"]').on('change', function () {
        var lis = $('#content li').hide(),
            check = $.map($('#attributes-Colors input[type="checkbox"]'), function (el,i) {
                if (el.checked) return $(el).data('color');
            }),
            isAll = $.inArray('All', check) != -1;

        if (check.length && !isAll) {
            $.each(check, function(i,color) {
                lis.filter(function() {
                    return $(this).data('color').indexOf(color) != -1
                }).show();
            });
        } else {
            lis.show();
        }
    });
});

FIDDLE