[英]jQuery/Javascript: Check all checkboxes on the following table
My original javascript was: 我原来的javascript是:
$(document).ready(function(){
$("th :checkbox").change(function() {
$(this).closest("table").find(":checkbox").prop("checked", $(this).is(":checked"));
});
});
which was used on a setting like this: 这是在这样的设置上使用:
<div>
<table id="table" width="100%">
<tr>
<th><input type="checkbox" />Select All</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
</table>
</div>
I slightly changed how my tables were and it now goes something like: 我略微改变了我的表格,现在它变成了:
<table>
<tr>
<th><input type="checkbox" />select all</th>
</tr>
</table>
<table>
<tr>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td><input type="checkbox" /></td>
</tr>
</table>
What do I need to change in my javascript so that when the checkbox in <th>
is checked, all the checkboxes inside the <td>
's in the next table are checked? 我需要在javascript中更改什么,以便在选中<th>
中的复选框时,检查下一个表中<td>
内的所有复选框?
Thanks. 谢谢。
Add .next()
to .closest("table")
: 将.next()
添加到.closest("table")
:
$(document).ready(function(){
$("th :checkbox").change(function() {
$(this).closest("table").next().find(":checkbox").prop("checked", $(this).is(":checked"));
});
});
$(this).closest("table")
selects the table of the element matching th :checkbox
. $(this).closest("table")
选择与th :checkbox
匹配的元素的表th :checkbox
。 next()
selects the next element, which is another table, in this case. next()
选择下一个元素,在这种情况下是另一个表。
This code can break easily. 这段代码很容易破解。 I suggest to set an ID to the other table, and use the following code: 我建议将ID设置为另一个表,并使用以下代码:
$(document).ready(function(){
$("th :checkbox").change(function() {
$("#id-of-table :checkbox").prop("checked", $(this).is(":checked"));
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.