首页 > 解决方案 > 如何在TD标签中添加id?

问题描述

我正在使用 DataTables 插件(我是初学者),我想在<td>HTML 标记中添加一个“id”。我做了这篇文章中的内容,但这不是我想要的。

我也看到了这篇文章,但我不知道如何使用此代码。

JS:

$('#datatable').dataTable({
    "sPaginationType" : "full_numbers",
    "createdRow" : function ( row, data_use, dataIndex ) {
        $(row).attr('id', dataIndex);
    },
    data : data_use,
    columns : column_name,
    dom : 'Bfrtip',
    select : 'single',
    responsive : true,
    altEditor : true,
    destroy : true,
    searching: true,
    buttons : [{
        extend : 'selected',
        text : 'Edit',
        name : 'edit'
    }],
});

标签: javascriptjquerydatatables

解决方案


您可以通过columnDefs在 DataTable 配置中添加一个数组并添加一个createdCell 函数来做到这一点。例如:

$(document).ready(function() {
  var table = $('#example').DataTable({
    'columnDefs': [{
      'targets': "_all",    // this will invoke the below function on all cells
      'createdCell': function(td, cellData, rowData, row, col) {
        // this will give each cell an ID
        $(td).attr('id', 'cell-' + cellData);
      }
    }]
  });

运行下面的代码片段以查看完整的示例。您可以右键单击一个单元格(即 a td)并单击“检查”以查看id添加到每个单元格的属性。

$(document).ready(function() {
  var table = $('#example').DataTable({
    'columnDefs': [{
      'targets': "_all",
      'createdCell': function(td, cellData, rowData, row, col) {
        $(td).attr('id', 'cell-' + cellData);
      }
    }]
  });

  // Add some data to the table
  table.row.add(['Airi Satou', 'Accountant', 'Tokyo', '5407', '2008/11/28', '$162,700']).draw();

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.js"></script>
<link href="https://cdn.datatables.net/r/dt/dt-1.10.9/datatables.min.css" rel="stylesheet" />
<table id="example" class="display" cellspacing="0" width="100%">
  <thead>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
      <th>Extn.</th>
      <th>Start date</th>
      <th>Salary</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
      <th>Extn.</th>
      <th>Start date</th>
      <th>Salary</th>
    </tr>
  </tfoot>
</table>


推荐阅读