javascript - 在单击事件上获取正确的 jquery 数据表对象
问题描述
我想通过点击事件从数据表中删除一行。我根据文档得到了这个,我的代码有效。但是,我不想在 remove 函数中硬编码我的数据表对象的变量名称,因为可能有多个或不同的数据表。如何确定应该删除行的正确对象?
根据@David Hedlund 的回答更新了codepen 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();
推荐阅读
- c# - 更新后设置不同?无法更改语言版本
- multilingual - Shopware 多语言类别
- amazon-redshift - 如何在带有 Redshift 的 SQL Workbench/J 中使用保存点?
- python - 仅当任何字符串的乞求在数据集中针对某些值不出现多次时才保留字符串行
- r - 将图例添加到具有 2 y 轴的图中
- android - 使用 gradle build application 构建 AOSP 项目
- laravel - laravel replicate() 方法和计算的数据库列
- android - tcomb-form-native 删除 android 上的下划线字段
- powershell - 活动目录显示未过期的锁定用户
- node.js - 如何设置虚拟麦克风并将音频从 node.js 传输到它