首页 > 解决方案 > 在单击事件上获取正确的 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>

标签: javascriptjquerydatatables

解决方案


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

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

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

推荐阅读