当你编写一个程序来切换所有复选框时,有没有一种方法可以不包括该组之外的其他复选框



我了解如何通过单击复选框或链接将所有复选框的状态切换为已选中或未选中。这是容易的部分。

但我也有几个复选框,我不想通过单击打开或关闭,它们不属于应该受到影响的组。这些复选框需要加以保护。

下面是一个例子。我可以单击底部复选框进行切换,但它应该只影响项目1到项目3复选框。当我单击底部复选框时,它不应该切换应该保护的前两个复选框。

谢谢。。。

$(function() {
$('#toggle-all').click(function(event) {
var selected = this.checked;
$(':checkbox').each(function() {
this.checked = selected;
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- These next two checkboxes should not be part of the checkboxes to be all toggled on or off -->
<input type='checkbox' name='notAssociated1'>This checkbox should be protected from ability to toggle all below<br>
<input type='checkbox' name='notAssociated2'>This checkbox should also be protected from ability to toggle all below<br><br>
<!-- The checkboxes below should be affected by clicking on the checkbox to toggle all on or off -->
<input type="checkbox" name="CB1" id="CB1" />Item 1<br>
<input type="checkbox" name="CB2" id="CB2" />Item 2<br>
<input type="checkbox" name="CB3" id="CB3" />Item 3<br>
<!-- select all boxes -->
<br><input type="checkbox" name="toggle-all" id="toggle-all" />Toggle Item 1 thru Item 3 but not the top two checkboxes

只要稍微修改一下代码,就可以只选择所需的checkbox输入。有多种方法可以实现这一点,但我选择用fieldset元素包围目标复选框(如果愿意,可以使用div元素或其他块级元素(,并使用.siblings()仅选择这些复选框。请参阅以下代码片段作为示例。

$(function() {
$('#toggle-all').click(function(event) {
var selected = this.checked;
$(this).siblings(":checkbox").each(function() {
this.checked = selected;
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- These next two checkboxes should not be part of the checkboxes to be all toggled on or off -->
<fieldset>
<input type='checkbox' name='notAssociated1'>This checkbox should be protected from ability to toggle all below<br>
<input type='checkbox' name='notAssociated2'>This checkbox should also be protected from ability to toggle all below<br><br>
</fieldset>
<!-- The checkboxes below should be affected by clicking on the checkbox to toggle all on or off -->
<fieldset>
<input type="checkbox" name="CB1" id="CB1" />Item 1<br>
<input type="checkbox" name="CB2" id="CB2" />Item 2<br>
<input type="checkbox" name="CB3" id="CB3" />Item 3<br>
<!-- select all boxes -->
<br><input type="checkbox" name="toggle-all" id="toggle-all" />Toggle Item 1 thru Item 3 but not the top two checkboxes
</fieldset>

如果您希望保留原始布局,可以使用其他选择器来针对您想要的选择器。在您的情况下,您可以使用$("[id^=CB]")进行选择,或者为每个复选框元素设置类,然后使用$(".selectAllCB")或您想要的任何类名进行选择。

如果使用jQuery选择器,则可以通过id或class对复选框进行分组。例如使用:

$('.class-group')...

(我心里有点不舒服!(

最新更新