如何在TD标签中添加id?

Seb*_*ard 1 javascript jquery datatables

我正在使用 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'
    }],
});
Run Code Online (Sandbox Code Playgroud)

And*_*bie 6

您可以通过将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);
      }
    }]
  });
Run Code Online (Sandbox Code Playgroud)

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

$(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);
      }
    }]
  });
Run Code Online (Sandbox Code Playgroud)
$(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();

});
Run Code Online (Sandbox Code Playgroud)