0

我正在尝试根据是否选中某些复选框来过滤 div 项目,默认情况下将选中所有复选框。

我已经设法使过滤工作,但如果没有找到结果(如果没有选中复选框),我正在努力附加一条错误消息

未找到结果,请重置过滤器并重新搜索

我把我的代码放在这里http://jsfiddle.net/3WcDC/25/

提前感谢任何可以帮助我的人,非常感谢。

HTML

<div id="CategoryContent">


<div class="product">Brand1</div>
<div class="product">Brand2</div>
<div class="product">Brand3</div>
<div class="product">Brand4</div>    


    <h2>Brands:</h2>
<input type="checkbox" name="brand" value="Brand1"/>Brand1 </br>
<input type="checkbox" name="brand" value="Brand2"/>Brand2 </br>
<input type="checkbox" name="brand" value="Brand3"/>Brand3 </br>    
<input type="checkbox" name="brand" value="Brand4"/>Brand4 </br>


</div>

用于过滤的javascript:

var $filters = $("input:checkbox[name='brand']").prop('checked', true); // start all checked
var $categoryContent = $('#CategoryContent div');
$filters.click(function() {
    // if any of the checkboxes for brand are checked, you want to show div's containing their value, and you want to hide all the rest.
    $categoryContent.hide();
    $filters.filter(':checked').each(function(i, el) {
        $categoryContent.filter(':contains(' + el.value + ')').show();
    });
});
4

1 回答 1

2

这就是你想要的:JSFiddle

HTML

<div id="CategoryContent">
     <h2 id="errorMessage">No results found, Please reset filter and search again</h2>

    <div class="product">Brand1</div>
    <div class="product">Brand2</div>
    <div class="product">Brand3</div>
    <div class="product">Brand4</div>
    <br>
    <br>
    <br>
    <br>
    <br>
     <h2>Brands:</h2>

    <input type="checkbox" name="brand" value="Brand1" />Brand1</br>
    <input type="checkbox" name="brand" value="Brand2" />Brand2</br>
    <input type="checkbox" name="brand" value="Brand3" />Brand3</br>
    <input type="checkbox" name="brand" value="Brand4" />Brand4</br>
</div>

jQuery

var $filters = $("input:checkbox[name='brand']").prop('checked', true), // start all checked
    $categoryContent = $('#CategoryContent div'),
    $errorMessage = $('#errorMessage');

$filters.click(function () {
    // if any of the checkboxes for brand are checked, you want to show div's containing their value, and you want to hide all the rest.
    $categoryContent.hide();
    var $selectedFilters = $filters.filter(':checked');
    if ($selectedFilters.length > 0) {
        $errorMessage.hide();
        $selectedFilters.each(function (i, el) {
            $categoryContent.filter(':contains(' + el.value + ')').show();
        });
    } else {
        $errorMessage.show();
    }

});

CSS

#CategoryContent {
    width:920px;
    margin:auto;
}
.product {
    width:50px;
    height:50px;
    display:block;
    margin-bottom:10px;
    margin-right:10px;
    background:red;
    float:left;
}
#errorMessage {
    display: none;
}
于 2013-05-13T07:25:39.600 回答