产品上的jQuery输入复选框过滤器

时间:2014-02-20 20:28:36

标签: javascript jquery html css

我编写了一个小脚本,当单击该复选框时,该脚本目前仅在产品上运行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();
    });
});
});

3 个答案:

答案 0 :(得分:3)

只需按类正确添加检查和过滤

$(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/

答案 1 :(得分:0)

如果我理解正确,则复选框ID与您尝试显示的元素类相同。

试试这个:

$(document).ready(function () {
$('.post').show();

$('.menu-item').find('input:checkbox').on('click', function () {
    $('.post').hide();

    $('.' + $(this).attr('id') ).show();
});
});

答案 2 :(得分:0)

您可以收听复选框更改,并仅显示已选中复选框:

$('.menu-item :input').change(function(){
    $('.post').hide(); 
    if( $(this).is(':checked') ){
        $('.post.'+$(this).attr('id')).show();   
    }
});

Fiddle