gpt4 book ai didi

javascript - 选择特定范围内的所有复选框?

转载 作者:太空宇宙 更新时间:2023-11-03 22:36:05 24 4
gpt4 key购买 nike

这是我的代码:

 $(".all_checkboxes").click(function () {
$('input:checkbox').not(this).prop('checked', this.checked);
});
td, th{
border: 1px solid gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h2>Section 1:</h2>
<table>
<tr>
<th><input type="checkbox" class="all_checkboxes" /></th>
<th>Names</th>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>twitter</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>instagram</td>
</tr>
</table>

<h2>Section 2:</h2>
<table>
<tr>
<th><input type="checkbox" class="all_checkboxes" /></th>
<th>Ids</th>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>454756</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>547498</td>
</tr>
</table>

我的问题在上面的 fiddle 中几乎很清楚。如您所见,目前这两个部分中的所有复选框都将被选中。我需要做的就是为 jQuery 选择器定义一个范围。我该怎么做?

最佳答案

$('input:checkbox') 将搜索所有复选框。您必须导航到最近的 table 并在其中搜索复选框。

$(".all_checkboxes").click(function () {
$(this)
.closest('table')
.find('input:checkbox')
.not(this)
.prop('checked', this.checked);
});
td, th{
border: 1px solid gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h2>Section 1:</h2>
<table>
<tr>
<th><input type="checkbox" class="all_checkboxes" /></th>
<th>Names</th>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>twitter</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>instagram</td>
</tr>
</table>

<h2>Section 2:</h2>
<table>
<tr>
<th><input type="checkbox" class="all_checkboxes" /></th>
<th>Ids</th>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>454756</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>547498</td>
</tr>
</table>

关于javascript - 选择特定范围内的所有复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46441685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com