gpt4 book ai didi

javascript - 按类别选择所有复选框,类别递增

转载 作者:行者123 更新时间:2023-11-28 04:44:26 25 4
gpt4 key购买 nike

我有一个 html 表,它为每个主机递增类,这样每个主机和子主机都具有相同的类,如下所示:

+-------------+--------------+
| host | child host |
+-------------+--------------+
| class=host0 | class=host0 |
+-------------+--------------+
| | class=host0 |
+-------------+--------------+
| | class=host0 |
+-------------+--------------+
| class=host1 | class=host1 |
+-------------+--------------+
| | class=host1 |
+-------------+--------------+

每个主机/子主机都有一个复选框。

<input class='host{$hostcount}'type='checkbox'>

我希望主机复选框选择所有子主机。下面的代码适用于 host0,我怎样才能让它适用于任何主机?

$(document).ready(function() {
$('.host0').change(function () {
if ($(this).prop('checked')) {
$('.host0:checkbox').prop('checked', true);
} else {
$('.host0:checkbox').prop('checked', false);
}
});
$('#selectAllHost').trigger('change');
});

最佳答案

我会给他们父/子类,从类名中删除数字,而是为数字添加一个数据属性,这样您就可以更轻松地定位它们。

$(document).ready(function() {

// change a parent checkbox
$('.host.parent').change(function() {

// grab the id and checked value
const id = $(this).data('id');
const checked = $(this).prop('checked');

// toggle all the children with the same id
$(`.host.child[data-id=${id}]`).prop('checked', checked ? true : false);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>0<input class="host parent" data-id="0" type="checkbox" /></td>
<td><input class="host child" data-id="0" type="checkbox" /><input class="host child" data-id="0" type="checkbox" /></td>
</tr>
<tr>
<td>1<input class="host parent" data-id="1" type="checkbox" /></td>
<td><input class="host child" data-id="1" type="checkbox" /><input class="host child" data-id="1" type="checkbox" /></td>
</tr>
</table>

关于javascript - 按类别选择所有复选框,类别递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53109577/

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