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

$('input[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:checked.yourClassName").each(function(){
   console.log($(this).val());
});

这也是工作。

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

这将获得类名为“yourClass”的所有复选框。我喜欢这个例子,因为它使用jQuery选择器检查,而不是做条件检查。就我个人而言,我也会使用数组来存储值,然后根据需要使用它们,比如:

var arr = [];
$('input.yourClass:checkbox:checked').each(function () {
    arr.push($(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');
        }
    });
});