Javascript 仅为选中复选框的行从行中选择数据属性
我有表有两列:复选框和名称Javascript 仅为选中复选框的行从行中选择数据属性,javascript,jquery,Javascript,Jquery,我有表有两列:复选框和名称 <table id="data"> <tr class="header"> <th> <input type="checkbox" class="download" /> </th> <th>Name</th> </tr> <tr data-id="1">
<table id="data">
<tr class="header">
<th>
<input type="checkbox" class="download" />
</th>
<th>Name</th>
</tr>
<tr data-id="1">
<td>
<input type="checkbox" class="download" />
</td>
<td>One</td>
</tr>
<tr data-id="2">
<td>
<input type="checkbox" class="download" />
</td>
<td>Two</td>
</tr>
<tr data-id="3">
<td>
<input type="checkbox" class="download" />
</td>
<td>Something</td>
</tr>
</table>
这很好,但是可以做得更好/更快吗?
这是我的工作演示:
另外,当正文中的一个或多个复选框被取消选中时,我如何取消选中标题中的复选框,并在所有复选框都被选中时选中它
编辑:感谢@tymeJV:
$(document).on('change', "#data tr.header input.download", function (e) {
$('#data tbody tr:not(.header) input.download').prop('checked', $(this).is(":checked"));
});
$(document).on('change', "#data tr:not(.header) input.download", function (e) {
if ($(this).is(":checked") && $('#data tr:not(.header) input.download:not(:checked)').length == 0) {
$('#data tbody tr.header input.download').prop('checked', true);
} else {
$('#data tbody tr.header input.download').prop('checked', false);
}
});
$(document).on('click', "#select", function (e) {
var rows = $("#data tr:not(.header) td input:checked").map(function () {
return $(this).closest("tr").data("id");
}).get();
console.log(rows);
});
你可以做:
var rows = $("#data tr:not(.header) td input:checked").map(function() {
return $(this).closest("tr").data("id");
}).get();
它仍在迭代,但仅检查行。您可以执行以下操作:
var rows = $("#data tr:not(.header) td input:checked").map(function() {
return $(this).closest("tr").data("id");
}).get();
它仍在迭代,但仅检查行。您可以执行以下操作:
var rows = $("#data tr:not(.header) td input:checked").map(function() {
return $(this).closest("tr").data("id");
}).get();
它仍在迭代,但仅检查行。您可以执行以下操作:
var rows = $("#data tr:not(.header) td input:checked").map(function() {
return $(this).closest("tr").data("id");
}).get();
它仍在迭代,但仅检查行。您可以使用:
$(".download:checkbox").map(function() {
return $(this).parents('tr').data('id');
}).get()
您可以使用:
$(".download:checkbox").map(function() {
return $(this).parents('tr').data('id');
}).get()
您可以使用:
$(".download:checkbox").map(function() {
return $(this).parents('tr').data('id');
}).get()
您可以使用:
$(".download:checkbox").map(function() {
return $(this).parents('tr').data('id');
}).get()
这看起来很快:第二部分呢?如果我在正文中至少取消选中一个复选框,如何取消选中标题中的复选框?更多的代码@Misiu-将更改附加到您的复选框,每次选中时,您都必须设置顶级复选框的状态。现在了解了:但我需要检查正文中的所有复选框是否都已选中。这看起来很快:第二部分呢?如果我在正文中至少取消选中一个复选框,如何取消选中标题中的复选框?更多的代码@Misiu-将更改附加到您的复选框,每次选中时,您都必须设置顶级复选框的状态。现在了解了:但我需要检查正文中的所有复选框是否都已选中。这看起来很快:第二部分呢?如果我在正文中至少取消选中一个复选框,如何取消选中标题中的复选框?更多的代码@Misiu-将更改附加到您的复选框,每次选中时,您都必须设置顶级复选框的状态。现在了解了:但我需要检查正文中的所有复选框是否都已选中。这看起来很快:第二部分呢?如果我在正文中至少取消选中一个复选框,如何取消选中标题中的复选框?更多代码@Misiu-将更改附加到您的复选框中,每次选中时,您都必须设置顶级复选框的状态。现在知道了:但我需要检查正文中的所有复选框是否都已选中。