【问题标题】:jQuery checkbox selection with multiple selections带有多个选择的jQuery复选框选择
【发布时间】:2014-12-28 03:23:52
【问题描述】:

当我选择 2 个或更多复选框时,我的 jQuery 复选框选择出现了一些问题。我还是前端编程的新手,所以请多多包涵。

在一个复选框上选择/取消选择效果很好,但是问题在于选择多个选择时:

1) 当我选择第一个复选框和另一个第二个复选框时,它会给出除第二个选择之外的所有选择。

2) 当我取消选择第二个复选框时,第一个复选框仍然选中,它给了我所有选择。

看来我必须在框上选择两次才能正确注册并给我正确的过滤选择。

这里的代码: JSFiddle

HTML

<div class="tags">
<label>
    <input type="checkbox" rel="accounting" />Accounting</label>
<label>
    <input type="checkbox" rel="courier" />Courier</label>
<label>
    <input type="checkbox" rel="project-management" />Project Management</label>
<label>
    <input type="checkbox" rel="video-games" />Video Games</label>
</div>
<ul class="results">
<li class="accounting" style="list-style-type:none"><a href="http://cnn.com" style="text-decoration: none">Accounting</a></li>
<li class="courier" style="list-style-type:none"><a href="http://cnn.com" style="text-decoration: none">Courier</a></li>
<li class="project-management" style="list-style-type:none"><a href="http://cnn.com" style="text-decoration: none">Project Management</a></li>
<li class="video-games" style="list-style-type:none"><a href="http://cnn.com" style="text-decoration: none">Video Games</a></li>
</ul>

jQuery

$(document).ready(function () {
$('div.tags').find('input:checkbox').live('click', function () {
    if ($(this).prop("checked")) {
        $('.results > li').toggle('show');
        $('div.tags').find('input:checked').each(function () {
            $('.results > li.' + $(this).attr('rel')).toggle('show');
        });
    } else{
       $('.results > li').show();
    }
});
});

【问题讨论】:

标签: jquery html checkboxlist


【解决方案1】:

这似乎可以满足您的需要:

$('div.tags').find('input:checkbox').on('click', function () {
    var vals = $('input:checkbox:checked').map(function () {
        return $(this).attr('rel');
    }).get();
    $('li').hide().filter(function () {
        return ($.inArray($(this).attr('class'), vals) > -1)
    }).show()
    if ($('input:checkbox:checked').length == 0) $('li').show()
});

jsFiddle example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-08
    • 2023-03-28
    • 2020-10-17
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    相关资源
    最近更新 更多