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

$('input[type=checkbox]').each(function () {
    var sThisVal = (this.checked ? $(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

其他回答

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

这也是工作。

 $('input.theclass[type=checkbox]').each(function () {
   var sThisVal = (this.checked ? $(this).val() : "");
 });
$(document).ready(function(){
    $('input.checkD[type="checkbox"]').click(function(){
        if($(this).prop("checked") == true){
            $(this).val('true');
        }
        else if($(this).prop("checked") == false){
            $(this).val('false');
        }
    });
});
$('input:checkbox.class').each(function () {
       var sThisVal = (this.checked ? $(this).val() : "");
  });

一个要演示的例子。

:checkbox是复选框的选择器(事实上,你可以省略选择器的输入部分,尽管我发现在库的早期版本中,你会得到奇怪的结果。我相信它们在后来的版本中得到了修复)。 .class是包含class的元素class属性的选择器。

你可以这样使用: HTML:

<div><input class="yourClass" type="checkbox" value="1" checked></div>
<div><input class="yourClass" type="checkbox" value="2"></div>
<div><input class="yourClass" type="checkbox" value="3" checked></div>
<div><input class="yourClass" type="checkbox" value="4"></div>

JQuery:

$(".yourClass:checkbox").filter(":checked")

它将选择1和3的值。