我正在尝试根据是否选中某些复选框来过滤div项目,默认情况下都会检查所有项目。
我设法让过滤工作但是如果没有找到结果(如果没有选中复选框,我很难附加错误消息)
未找到结果,请重置过滤器并再次搜索
我已将代码放在http://jsfiddle.net/3WcDC/25/
感谢先进的任何可以帮助我的人,非常感谢。
<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>
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();
});
});
答案 0 :(得分: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;
}