1

I have a container which contains divs of the same format. Each div has 3 attributes in which I am applying filter options to.

the div looks like this

<div data-A="1" data-B="x" data-C="4">

Each of the 3 options, A B and C has values for each option. For example A has values 1 2 3, B has values x y z, C has values 4 5 6. They are available as checkboxes like this

So if I checked an A option with value = 1, the div that has data-A = 1 will show, so if I checked A option with value = 1, B option with value = x and C option with value = z, divs that fulfil these 3 values will be shown.

However, how do I actually cater to situations in which one of the A,B and C is not chosen as a filter at all, ie checked B option with value = x and C option with value = 4, so I should be showing all divs with data-B = 'x' and data-C = '4'.

right now, I am using 3 nested for loops for this, which will not cater to the situation in which one option is not chosen. Is there any way to do this efficiently?

My jquery for now is as below

for(var p = 0;p < $(A).length ;p++)
    {
        for(var q = 0;q < $(B).length ;q++)
        {
            for(var r = 0;r < $(C).length ;r++)
            {
                $('div[data-A = "'+ A[p] + '"][data-B="'+ B[q] +'"][data-C="'+ C[r] +'"]').show();
            }
        }
    }
4

1 回答 1

0

我会采取的方法是听取整体变化并将显示相应地切换到最后一个已更改的复选框。

类似的东西:

/*Put whatever is needed to select your checkboxes of the A family here*/
$("input[type='checkbox'].A").on("change", function(){
    if (this.checked) {
        $("div[data-A='" + this.value + "']").each(function(index, elt) {
            /*This is pseudo code, you'll need to put here a way to select the correct checkbox and to check if it's checked*/
            if ($(elt).data("B").isChecked && $(elt).data("C").isChecked) {
                $(elt).show();
            } else {
                $(elt).hide();
            }
        }
    } else {
        $("div[data-A='" + this.value + "']").hide()
    }
});

您可以为每个函数创建一个单独的函数,也可以data-X对其进行一些分解以避免冗余。

于 2013-04-29T08:52:02.203 回答