Jquery复选框过滤 - 修复

时间:2014-11-29 13:30:45

标签: javascript jquery checkbox filtering

我找到了一个需要jquery过滤的脚本。 在该脚本中,某些项目的值为绿色,一些为绿色和黄色。如果您选择绿色和黄色的颜色,您将获得所有绿色和黄色项目,以及绿色和黄色项目。 我需要改变它,这样如果我选择绿色和黄色,我只会得到绿色和黄色的项目。

我不是很擅长js,所以我非常感谢你的帮助。

var byProperty = [], byColor = [], byLocation = [];

    $("input[name=fl-colour]").on( "change", function() {
        if (this.checked) byProperty.push("[data-category~='" + $(this).attr("value") + "']");
        else removeA(byProperty, "[data-category~='" + $(this).attr("value") + "']");
    });

    $("input[name=fl-size]").on( "change", function() {
        if (this.checked) byColor.push("[data-category~='" + $(this).attr("value") + "']");
        else removeA(byColor, "[data-category~='" + $(this).attr("value") + "']");
    });

    $("input[name=fl-cont]").on( "change", function() {
        if (this.checked) byLocation.push("[data-category~='" + $(this).attr("value") + "']");
        else removeA(byLocation, "[data-category~='" + $(this).attr("value") + "']");
    });

    $("input").on( "change", function() {
        var str = "Include items \n";
        var selector = '', cselector = '', nselector = '';

        var $lis = $('.flowers > div'),
            $checked = $('input:checked');  

        if ($checked.length) {  

            if (byProperty.length) {        
                if (str == "Include items \n") {
                    str += "    " + "with (" +  byProperty.join(',') + ")\n";               
                    $($('input[name=fl-colour]:checked')).each(function(index, byProperty){
                        if(selector === '') {
                            selector += "[data-category~='" + byProperty.id + "']";                     
                        } else {
                            selector += ",[data-category~='" + byProperty.id + "']";    
                        }                
                    });                 
                } else {
                    str += "    AND " + "with (" +  byProperty.join(' OR ') + ")\n";                
                    $($('input[name=fl-size]:checked')).each(function(index, byProperty){
                        selector += "[data-category~='" + byProperty.id + "']";
                    });
                }                           
            }

            if (byColor.length) {                       
                if (str == "Include items \n") {
                    str += "    " + "with (" +  byColor.join(' OR ') + ")\n";                   
                    $($('input[name=fl-size]:checked')).each(function(index, byColor){
                        if(selector === '') {
                            selector += "[data-category~='" + byColor.id + "']";                    
                        } else {
                            selector += ",[data-category~='" + byColor.id + "']";   
                        }                
                    });                 
                } else {
                    str += "    AND " + "with (" +  byColor.join(' OR ') + ")\n";               
                    $($('input[name=fl-size]:checked')).each(function(index, byColor){
                        if(cselector === '') {
                            cselector += "[data-category~='" + byColor.id + "']";                   
                        } else {
                            cselector += ",[data-category~='" + byColor.id + "']";  
                        }                   
                    });
                }           
            }

            if (byLocation.length) {            
                if (str == "Include items \n") {
                    str += "    " + "with (" +  byLocation.join(' OR ') + ")\n";                
                    $($('input[name=fl-cont]:checked')).each(function(index, byLocation){
                        if(selector === '') {
                            selector += "[data-category~='" + byLocation.id + "']";                     
                        } else {
                            selector += ",[data-category~='" + byLocation.id + "']";    
                        }                
                    });             
                } else {
                    str += "    AND " + "with (" +  byLocation.join(' OR ') + ")\n";                
                    $($('input[name=fl-cont]:checked')).each(function(index, byLocation){
                        if(nselector === '') {
                            nselector += "[data-category~='" + byLocation.id + "']";                    
                        } else {
                            nselector += ",[data-category~='" + byLocation.id + "']";   
                        }   
                    });
                }            
            }

            $lis.hide(); 
            console.log(selector);
            console.log(cselector);
            console.log(nselector);

            if (cselector === '' && nselector === '') {         
                $('.flowers > div').filter(selector).show();
            } else if (cselector === '') {
                $('.flowers > div').filter(selector).filter(nselector).show();
            } else if (nselector === '') {
                $('.flowers > div').filter(selector).filter(cselector).show();
            } else {
                $('.flowers > div').filter(selector).filter(cselector).filter(nselector).show();
            }

        } else {
            $lis.show();
        }   

        $("#result").html(str); 

    });

    function removeA(arr) {
        var what, a = arguments, L = a.length, ax;
        while (L > 1 && arr.length) {
            what = a[--L];
            while ((ax= arr.indexOf(what)) !== -1) {
                arr.splice(ax, 1);
            }
        }
        return arr;
    }

链接到jsfiddle:http://jsfiddle.net/3gf1j1ec/

1 个答案:

答案 0 :(得分:0)

这是获取数组交集的方法。它使用Array.prototype.every方法生成匹配。



var byProperty = [], byColor = [], byLocation = [];
		
var intersectionOfColours = function(){
    
    //    get an array of the selected colours
    var selectedColours = $('form input[name="fl-colour"]:checked').map(function(){
        return this.value;
    }).get();
    
    //    iterate through the flowers and show/hide
    $('.flowers .flower').each(function(){
        var flowerColours = $(this).data("category").split(' ');
        //    if all selected colours can be found in flowerColours, we have a match
        var match = selectedColours.every(function(thisColour){
            return (flowerColours.indexOf(thisColour) !== -1);
        });
        if (match) {
            $(this).show();
        } else {
            $(this).hide();
        }
    });
    
    // debug
    $('#result').html( JSON.stringify(selectedColours) );
};

$("input[name=fl-colour]").on( "change", intersectionOfColours);

label {
    float: left;
    clear: left;
}

.flowers-wrap {
    width: 100%;
}

.flowers-wrap form {
    width: 49%;
    float: left;
}

.flower {
    background-color: #DEE;
    padding: .5em;
    margin: 3px;
    border: 1px solid gray;
}

.flowers {
    width: 49%;
    float: left;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<pre id=result></pre>

<div class="flowers-wrap">
    
    <h3>Available Flowers</h3>
    <p><strong>Filter flowers by colour:</strong></p>
    <form>
        <label><input type="checkbox" name="fl-colour" value="red" id="red" />Red</label>
        <label><input type="checkbox" name="fl-colour" value="yellow" id="yellow" />Yellow</label>
        <label><input type="checkbox" name="fl-colour" value="pink" id="pink" />Pink</label>
        <label><input type="checkbox" name="fl-colour" value="purple" id="purple" />Purple</label>
        <label><input type="checkbox" name="fl-colour" value="green" id="green" />Green</label>
        <label><input type="checkbox" name="fl-colour" value="other" id="other" />Other</label>
    </form>
        
    <div class="flowers">
        <div class="flower" data-id="aloe" data-category="green small medium africa">Aloe</div>
        <div class="flower" data-id="lavendar" data-category="purple green medium africa europe">Lavender</div>
        <div class="flower" data-id="stinging-nettle" data-category="green large africa europe asia">Stinging Nettle</div>
        <div class="flower" data-id="gorse" data-category="green yellow large europe">Gorse</div>  
        <div class="flower" data-id="hemp" data-category="green large asia">Hemp</div>  
        <div class="flower" data-id="titan-arum" data-category="purple other giant asia">Titan Arum</div>  
        <div class="flower" data-id="golden-wattle" data-category="green yellow large australasia">Golden Wattle</div>  
        <div class="flower" data-id="purple-prairie-clover" data-category="purple green other medium north-america">Purple Prairie Clover</div> 
        <div class="flower" data-id="camellia" data-category="pink other large north-america">Camellia</div> 
        <div class="flower" data-id="scarlet-carnation" data-category="red medium north-america">Scarlet Carnation</div> 
        <div class="flower" data-id="indian-paintbrush" data-category="red medium north-america">Indian Paintbrush</div>  
        <div class="flower" data-id="moss-verbena" data-category="purple other small south-america">Moss Verbena</div>  
        <div class="flower" data-id="climbing-dayflower" data-category="blue tiny south-america">Climbing Dayflower</div>  
        <div class="flower" data-id="antarctic-pearlwort" data-category="green yellow large antarctica">Antarctic Pearlwort</div>                 	
    </div>
    
</div>
&#13;
&#13;
&#13;

相关问题