我想制定一个逻辑,如果选中了子复选框,它也会检查父复选框。输入可以是父级、子级以及两者:
<input type="checkbox" name="checkbox[$counter]" class="parent" />
<input type="checkbox" name="checkbox[$counter]" class="child" />
<input type="checkbox" name="checkbox[$counter]" class="parent child" />
这个结构:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 5
看起来像这样:
<table class="table">
<tr>
<td>
<input type="checkbox" name="checkbox[1]" class="parent" />
</td>
<td>
.
.
</tr>
<tr>
<td>
<input type="checkbox" name="checkbox[2]" class="child" />
</td>
<td>
.
.
</tr>
<tr>
<td>
<input type="checkbox" name="checkbox[3]" class="child" />
</td>
<td>
.
.
</tr>
<tr>
<td>
<input type="checkbox" name="checkbox[4]" class="parent" />
</td>
<td>
.
.
</tr>
<tr>
<td>
<input type="checkbox" name="checkbox[5]" class="child parent" />
</td>
<td>
.
.
</tr>
<tr>
<td>
<input type="checkbox" name="checkbox[6]" class="child" />
</td>
<td>
.
.
</tr>
<tr>
<td>
<input type="checkbox" name="checkbox[7]" class="child" />
</td>
<td>
.
.
</tr>
</table>
我希望如果我检查 3,它会检查 1,如果我检查 6,它也会检查 5 和 4。
此外,复选框位于单独的表格行中,因为我想在复选框旁边显示表格中结构化的一些信息。
你能给我看一个脚本吗?我尝试了这个,但它不起作用:
$(document).ready(function() {
$('input.child').change(function() {
if ($(this).is(':checked')) {
$(this).closest('input.parent:checkbox').attr('checked', true);
}
});
});
最佳答案
复选框没有父子关系,因此方法.closest()
不会起作用,因为它从自身开始遍历。
我建议您使用 TR
元素分配类,并附加事件处理程序,遍历 DOM 会很容易。
<tr class="parent">...</tr>
<tr class="child">...</tr>
您可以使用 .prevAll()
的组合和 .first()
获取目标 TR
,然后使用 .find()
获取复选框。
此外,如果您想触发更改事件,可以使用 trigger()
方法。
$(document).ready(function() {
$('.child').on('change', ':checkbox', function() {
if ($(this).is(':checked')) {
var currentRow = $(this).closest('tr');
var targetedRow = currentRow.prevAll('.parent').first();
var targetedCheckbox = targetedRow.find(':checkbox');
targetedCheckbox.prop('checked', true).trigger('change');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
<tr class="parent">
<td>
<input type="checkbox" name="checkbox[1]" />
</td>
</tr>
<tr class="child">
<td>
<input type="checkbox" name="checkbox[2]" />
</td>
</tr>
<tr class="child">
<td>
<input type="checkbox" name="checkbox[3]" />
</td>
</tr>
<tr class="parent">
<td>
<input type="checkbox" name="checkbox[4]" />
</td>
</tr>
<tr class="child parent">
<td>
<input type="checkbox" name="checkbox[5]" />
</td>
</tr>
<tr class="child">
<td>
<input type="checkbox" name="checkbox[6]" />
</td>
</tr>
<tr class="child">
<td>
<input type="checkbox" name="checkbox[7]" />
</td>
</tr>
</table>
关于javascript - 如果子复选框被选中,jQuery 检查父复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49129566/