javascript 如何处理数据表中的复选框单击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30210612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to handle checkbox click event in datatables
提问by Willy
I have a boolean field like a flag to state that row is deleted or not in the table. It displayed using checkbox, so if the data has been deleted, the checkbox value is true and vice versa.
我有一个像标志一样的布尔字段来说明表中的行是否被删除。它使用复选框显示,因此如果数据已被删除,则复选框值为真,反之亦然。
Below is the code to display the table:
下面是显示表格的代码:
<table id="tblEvent" class="display" cellspacing="0" style="width: 100%">
<thead>
<tr>
<th>@Html.DisplayNameFor(model => model.PIC)</th>
<th>@Html.DisplayNameFor(model => model.Name)</th>
<th>@Html.DisplayNameFor(model => model.StartDate)</th>
<th>@Html.DisplayNameFor(model => model.Status)</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.PIC)</td>
<td>@Html.DisplayFor(modelItem => item.Name)</td>
<td>@Html.DisplayFor(modelItem => item.StartDate)</td>
<td>@Html.EditorFor(modelItem => item.Status)</td>
</tr>
}
</tbody>
</table>
$(document).ready(function () {
$("#tblEvent").dataTable({
"order": [[1, "desc"]]
});
});
In the table I can click the checkbox but I don't know how to handle the click event because I'm using datatables to display the data. How to handle checkbox event using datatable?
在表中,我可以单击复选框,但我不知道如何处理单击事件,因为我使用数据表来显示数据。如何使用数据表处理复选框事件?
回答by davidkonrad
I guess you are using a paginated table, and are facing the problem that your click handler not are working when you change pages?
我猜您正在使用分页表,并且遇到了当您更改页面时单击处理程序不起作用的问题?
The solution suggested in comments would work on a 1-page dataTable, but is useless if you change pages or the dataTable otherwise is redrawn :
评论中建议的解决方案适用于 1 页数据表,但如果您更改页面或重新绘制数据表则无用:
$('#tblEvent input[type="checkbox"]').click(function() {
console.log('suggested-in-comment', 'click');
});
...Only works on the first page. You must use a delegated eventto be sure that the checkboxes always is bound to the click-handler :
...仅适用于第一页。您必须使用委托事件来确保复选框始终绑定到点击处理程序:
$('#tblEvent').on('click', 'input[type="checkbox"]', function() {
console.log('best', 'click');
});
demo with both / proof of concept -> http://jsfiddle.net/o4mhqpr3/
演示/概念证明-> http://jsfiddle.net/o4mhqpr3/
回答by Tamás Mazuk
If you are using datatables with selection capabilitiesyou can use listeners (selectand deselectevents).
如果您使用具有选择功能的数据表,您可以使用侦听器(选择和取消选择事件)。
table.on( 'deselect', function ( e, dt, type, indexes ) {});
table.on( 'select', function ( e, dt, type, indexes ) {});