在单击事件时获取正确的 jquery 数据表对象



我想使用单击事件从数据表中删除一行。我根据文档得到了这个,我的代码可以工作。 但是,我不想在 remove 函数中对我的 datatable 对象的变量名称进行硬编码,因为可能存在多个或不同调用的数据表。如何确定应删除行的正确对象?

根据 @David Hedlund 的答案更新了代码笔 https://codepen.io/bintux/pen/QWLKxQG 中的代码。

var table = $('#example').DataTable();
$('.deleterow').on('click', function () {
//I want to avoid this hard coded name for the datatable object but instead get the right object when the user clicks in the table    
table
.row($(this).parents('tr'))
.remove()
.draw();
});

var table = $('#example').DataTable();
$('.deleterow').on('click', function() {
table
.row($(this)
.parents('tr'))
.remove()
.draw();
//console.log(row);
});
<link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.18/js/dataTables.bootstrap4.min.js"></script>
<div class="container">
<table id="example" class="display nowrap" width="100%">
<thead>
<tr>
<th>Remove</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Remove</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td><span class="deleterow">X</span></td>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$3,120</td>
</tr>
<tr>
<td><span class="deleterow">X</span></td>
<td>Garrett Winters</td>
<td>Director</td>
<td>Edinburgh</td>
<td>63</td>
<td>2011/07/25</td>
<td>$5,300</td>
</tr>
<tr>
<td><span class="deleterow">X</span></td>
<td>Donna Snider</td>
<td>System Architect</td>
<td>New York</td>
<td>27</td>
<td>2011/01/25</td>
<td>$3,120</td>
</tr>
</tbody>
</table>
</div>

.deleterow将永远是感兴趣表的子级。

在您的点击侦听器中,您可以像这样访问它:

var table = $(this).closest('table').DataTable();

最新更新