我知道我可以得到所有选中的复选框在页面上使用这个:

$('input[type=checkbox]').each(function () {
    var sThisVal = (this.checked ? $(this).val() : "");
});

但是我现在在一个有一些我不想包括的其他复选框的页面上使用这个。我如何更改上面的代码,以只查看选中的复选框上有特定的类?


当前回答

我不确定它是否对您的特定情况有帮助,我也不确定在您的情况下,您想要包含的复选框是否都是单个表单或div或表的一部分,但您总是可以选择特定元素中的所有复选框。例如:

<ul id="selective">
 <li><input type="checkbox" value="..." /></li>
 <li><input type="checkbox" value="..." /></li>
 <li><input type="checkbox" value="..." /></li>
 <li><input type="checkbox" value="..." /></li>
</ul>

然后,使用下面的jQuery,它只通过id="selective"的UL内的复选框:

$('#selective input:checkbox').each(function () {
 var sThisVal = (this.checked ? $(this).val() : "");
});

其他回答

$("input:checked.yourClassName").each(function(){
   console.log($(this).val());
});

这也是工作。

我知道这个问题已经有了很多很好的答案,但我在浏览时发现了这个,我发现它真的很容易使用。我想分享给其他想看的人。

HTML:

<fieldset>
    <!-- these will be affected by check all -->
    <div><input type="checkbox" class="checkall"> Check all</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
</fieldset>
<fieldset>
    <!-- these won't be affected by check all; different field set -->
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
</fieldset>

jQuery:

$(function () {
    $('.checkall').on('click', function () {
        $(this).closest('fieldset').find(':checkbox').prop('checked', this.checked);
    });
});

参考: 最简单的“检查所有”与jQuery

我不确定它是否对您的特定情况有帮助,我也不确定在您的情况下,您想要包含的复选框是否都是单个表单或div或表的一部分,但您总是可以选择特定元素中的所有复选框。例如:

<ul id="selective">
 <li><input type="checkbox" value="..." /></li>
 <li><input type="checkbox" value="..." /></li>
 <li><input type="checkbox" value="..." /></li>
 <li><input type="checkbox" value="..." /></li>
</ul>

然后,使用下面的jQuery,它只通过id="selective"的UL内的复选框:

$('#selective input:checkbox').each(function () {
 var sThisVal = (this.checked ? $(this).val() : "");
});
<input type="checkbox" id="Checkbox1" class = "chk" value = "1" />
<input type="checkbox" id="Checkbox2" class = "chk" value = "2" />
<input type="checkbox" id="Checkbox3" class = "chk" value = "3" />
<input type="checkbox" id="Checkbox4" class = "chk" value = "4" />
<input type="button" id="demo" value = "Demo" />

<script type = "text/javascript" src = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
    $("#demo").live("click", function () {
        $("input:checkbox[class=chk]:checked").each(function () {
            alert("Id: " + $(this).attr("id") + " Value: " + $(this).val());
        });
    });
</script>

http://www.jqueryfaqs.com/Articles/Get-values-of-all-checked-checkboxes-by-class-name-using-jQuery.aspx

你可以这样试试

let values = (function() {
                let a = [];
                $(".chkboxes:checked").each(function() {
                    a.push($(this).val());
                });
                return a;
            })();