我编写了这个jQuery片段来处理tr
单击,向其中添加一个引导类并单击其中的第一个checkbox
。
$('body').on('change', '.select-all-children', function(e) {
var checked = this.checked;
$('.select-child').each(function() {
$(this).prop('checked', checked);
if(checked) {
$(this).parent().parent().addClass('warning');
} else {
$(this).parent().parent().removeClass('warning');
}
});
});
$('body').on('click', '.table-selectable tbody tr', function(e) {
var checkbox = $(this).find('.select-child');
checkbox.click();
var checked = checkbox[0].checked;
if(checked) {
$(this).addClass('warning');
} else {
$(this).removeClass('warning');
}
});
$('body').on('change', '.select-child', function(e) {
var checked_total = $('.select-child:checked').length;
if(checked_total == $('.select-child').length) {
$('.select-all-children').prop('checked', true);
} else {
$('.select-all-children').prop('checked', false);
}
});
每当我单击tr
并因此触发此调用时:
checkbox.click();
我不能再单击复选框了,但是tr
单击很好。
这是表的HTML标记:
<table class="table table-selectable">
<thead>
<tr>
<th>
<input type="checkbox" class="select-all-children">
</th>
</tr>
</thead>
<tbody>
<tr>
<tr>
<td>
<input type="checkbox" class="select-child">
</td>
</tr>
</tr>
</tbody>
</table>
发布于 2016-04-16 21:15:40
您可以比您的方法简单得多,就像这样:
Handling selected复选框:(只需选中/取消选中行中的第一个复选框,并将warning
类添加到选定的行)。
$('.select-all-children').click(function (e) {
$(this).closest('table').find('tr td:first-child input:checkbox').prop('checked', this.checked);
if (this.checked){
$(this).closest('table').find('tbody tr').addClass('warning');
} else {
$(this).closest('table').find('tbody tr').removeClass('warning');
}
});
处理tr:上的单击(我们也可以使用toggleClass
而不是add/remove class
)。
$('.table-selectable tbody tr td:first-child input:checkbox').on('click', function(e) {
$(this).closest('tr').toggleClass('warning');
});
现在看看https://jsfiddle.net/Shady_Alset/9jLf9pga/,我希望它对你有用,谢谢。
发布于 2016-04-16 16:07:23
我已经像这样修改了代码,并且复选框运行得很好。请查看JQuery代码的更改和注释。
$('body').on('change',‘..select all-children’,函数(e) { var checked = this.checked;
$('.select-child').each(function () {
$(this).prop('checked', checked);
if (checked) {
$(this).parent().parent().addClass('warning');
} else {
$(this).parent().parent().removeClass('warning');
}
});
});
$('body').on('click', '.table-selectable tbody tr', function (e) {
var checkbox = $(this).find('.select-child');
//Old code commented:
//checkbox.click();
//Modified Code:
checked.click();
var checked = checkbox[0].checked;
if (checked) {
$(this).addClass('warning');
} else {
$(this).removeClass('warning');
}
});
$('body').on('change', '.select-child', function (e) {
var checked_total = $('.select-child:checked').length;
if (checked_total == $('.select-child').length) {
$('.select-all-children').prop('checked', true);
} else {
$('.select-all-children').prop('checked', false);
}
});
谢谢。
https://stackoverflow.com/questions/36666252
复制相似问题