使用 Jquery 选中基于 Div ID 和类的所有复选框

Check All Checkboxes based on Div Id and Class using Jquery

本文关键字:复选框 ID Div Jquery 使用      更新时间:2023-09-26

我想根据 Div ID 和复选框类选中所有复选框。不同div 中的所有复选框都具有相同的类。我想选中该特定div中按钮单击的所有复选框。我不想像下面这样使用输入[类型='复选框']。我只想使用类名。我可以这样做吗?

 $('div#'+Id+' input[type=checkbox]').each(function () {            
        $(this).prop('checked', true);
    });

下面是我的代码。

<div id="div1">
<input type="button" id="btnDiv1" value="Select All" />
<input type="checkbox" class="check" />Mark
<input type="checkbox" class="check" />Frank
</div>
<div id="div2">
<input type="button" id="btnDiv2" value="Select All" />
<input type="checkbox" class="check" />John
<input type="checkbox" class="check" />Travis
<input type="checkbox" class="check" /> Matt
</div>
<div id="div3">
<input type="button" id="btnDiv3" value="Select All" />
<input type="checkbox" class="check" />Lee
<input type="checkbox" class="check" />Charles
</div>

使用类选择器直接调用 'prop()' 方法,如下所示:

$('div#'+Id+' input.check').prop('checked', true);

编辑:

$('input[type=button]').click(function() {
   $(this).parent().find('.check').prop('checked', true);
});

你可以做这样的事情:

$('div').on('click',function(){
   $(this).find('input:not([type=button])').prop('checked',true);
});

演示

如果要在单击"全选"按钮时选择组内的所有复选框元素,则可以为"全选"元素指定一个通用类名,然后附加click事件侦听器。

您可以使用.nextAll()来选择所有后续.check元素:

这里的例子

$('.select-all').on('click', function () {
    $(this).nextAll('.check').prop('checked', true);
});

..或者,您可以选择最接近的div祖先,然后选择其中的所有.check元素:

这里的例子

$('.select-all').on('click', function () {
    $(this).closest('div').find('.check').prop('checked', true);
});

如果要根据单击的"全选"按钮id中的数字选择元素,则可以使用以下方法:

这里的例子

$('.select-all').on('click', function () {
    $('#div' + this.id.replace(/'D/g, '') +' .check').prop('checked', true);
});