1

I am trying to have <li>s hide and show based on their class names (most of which are multiple classes) selected by the user using a checkbox selector for individual attributes. I have noticed however that in my implementation, it looks for the attribute, and performs the task, regardless of all of the other attribute selectors on the form. How can I adjust the code so that it shows the <li>s based on visibility selections of the individual class attributes?

Here is the fiddle.

As you can see, if you check the 'A' box, it hides 'A', 'AB', 'AC', and 'ABC'. However the user thinks that any <li> with attributes 'B' and 'C' are visible, and 'AB', 'AC', and 'ABC' are hidden.

So if the user selects 'A' to be hidden, then the only <li> to be hidden is

'A'

, since it is the only one with just 'A', and 'B' and 'C' are attributes the user wants to be visible, leaving the following visible:

'B', 'C', 'AB', 'AC', 'BC', "ABC'

. If the user selects 'A' and 'B' to hide, then the following would be hidden:

'A', 'B', 'AB'

; and visible would be:

'C', 'AC', 'BC', and 'ABC'

, since they have a 'C' class attribute. I'm assuming I would have to make an array or something similar, and then look for any attributes within the array, and display/hide them accordingly.

4

2 回答 2

1

这是一种使用更少代码的方法:

http://fiddle.jshell.net/vnjHn/1/

$('form input').on('change', function() {

    var notSelectedList = $('form input:not(:checked)').map(function() {
        return '.' + $(this).attr('name');
    }).get().join(',');

    $('.viewing li').each(function() {
        $(this).toggle($(this).is(notSelectedList));
    });

});​

它通过建立一个不隐藏的类的逗号分隔列表来工作,然后检查这些类中的任何一个的所有列表项——我认为这是一种更简单的检查方法。

于 2012-07-09T21:23:17.377 回答
0

建立在您的示例之上是代码:

<form class="form">
    <p> Check to hide </p>
    <input type="checkbox" id="1" name="1" class="selector"/><label for="1">A</label>
    <input type="checkbox" id="2" name="2" class="selector"/><label for="2">B</label>
    <input type="checkbox" id="3" name="3" class="selector"/><label for="3">C</label>
</form><br>

<div class="viewing">
    <ul>
        <li class="1">A</li>
        <li class="2">B</li>
        <li class="3">C</li>
        <li class="1 2">AB</li>
        <li class="2 3">BC</li>
        <li class="1 3">AC</li>
        <li class="1 2 3">ABC</li>
    </ul>
</div>​

和js:

var classes = {'1':false,'2':false,'3':false};
$('form input').on('change', function() {
var itemClass= $(this).attr('name');
console.log(itemClass);
classes[itemClass] = $(this).attr('checked') == 'checked';    
    $('.viewing>ul>li').each(function(){
        var classList =$(this).attr('class').split(/\s+/);
        var hide = true;
        $.each( classList, function(index, item){
            if (classes[item] == false) {
hide = false;                

            };
});
        if(hide == true)
            $(this).hide();
        else
            $(this).show();
    });
});​

你可以在这里找到演示

于 2012-07-09T20:37:13.430 回答