首页 > 解决方案 > 动态获取数据表的 ID

问题描述

我想从数据表中提取表的 ID 而不在函数中指定表的名称。例如:而不是指定var tableName = $('#myTable').attr('name')我想在不写#myTable的情况下提取表名

$(document).ready(function() {

  $('#myTable').DataTable( {
    dom: 'Bfrtip',
    buttons: [
      { extend : 'collection',
        text : '<i class="fa fa-bars">buttons</i>',
        buttons: [
          'copy', 'csv', 'excel', 'pdf', 'print',
          {
            text: 'Report Issue',
            action: function ( e, dt, node, config ) {
              reportIssue(e, dt, node, config);
            }
          }
        ]
      }]
  } );

  // e - the button click event
  // dt - the datatable object
  // node - button node
  // config - the button's config (e.g. 'text')
  function reportIssue(e, dt, node, config) {    
    var tableName = $('#myTable').attr('name');
    alert( 'The "' + config.text + '" button was clicked\n' 
        + 'for the "' + tableName + '" table.' );
  }

});

标签: javascriptdatatables

解决方案


使用找到数据表容器dt.table().container(),然后在其中找到表:

function reportIssue(e, dt, node, config) {    
  var container = dt.table().container();
  var tableName = $(container).find("table").attr('name');
}

推荐阅读