我编写了一个小脚本,当前仅在单击复选框时在产品上运行 hide()。我似乎无法弄清楚如何在单击时只显示那些具有这些类名的特定产品。如果未单击任何内容,应显示所有产品。
JSFIDDLE: http://jsfiddle.net/mzvNL/
HTML:
<ul>
<li class="menu-item">
<label for="beans-palak">Beans Palak</label>
<input id="beans-palak" type="checkbox" />
<label for="bengal-lentils">Bengal Lentils</label>
<input id="bengal-lentils" type="checkbox" />
<label for="bombay-potatoes">Bombay-Potatoes</label>
<input id="bombay-potatoes" type="checkbox" />
</li>
<article class="post beans-palak">asd</article>
<article class="post bombay-potatoes">asd</article>
<article class="post bengal-lentils">asd</article>
<article class="post bombay-potatoes bengal-lentils">asd</article>
<article class="post bengal-lentils bombay-potatoes bengal-lentils">asd</article>
CSS:
article {
height: 100px;
width: 100px;
background: red;
margin: 10px;
display: inline-block;
JS:
$(document).ready(function () {
$('.post').show();
$('.menu-item').find('input:checkbox').on('click', function () {
$('.post').hide();
$('.menu-item').find('input:checked').each(function () {
$('.post ' + $('li.menu-item').find('input:checked').attr('id')).show();
});
});
});
正确添加检查和按类过滤
$(document).ready(function () {
$('.post').show();
$('.menu-item').find('input:checkbox').on('click', function () {
var post = $('.post').hide();
var elements = $('.menu-item').find('input:checked');
if(elements.length){
elements.each(function () {
post.filter('.' + this.id).show();
});
}
else
post.show();
});
});
http://jsfiddle.net/mzvNL/1/
我是一名优秀的程序员,十分优秀!