使用 table 的 ID 访问数据表 API

Access DataTables API using the table's id

我使用 jQuery UI 标签。我在每个新选项卡中都有一个数据表。我想将在对话框中选择的行添加到当前选项卡中的 table。
因为我在选项卡内有那些 tables,这些选项卡的名称与我用于选项卡的编号相同(例如 "tabs-1" 将包含 table "choice1"),所以我宁愿找到所需的 table 每次我需要添加行而不是将所有这些 table 变量存储在集合中时。
如果您确切并且明确地知道在初始化时访问已经初始化的数据表而不存储在变量中是不可能,请建议一种存储方法,因为我唯一想到的是一个对象,其中键是包含选项卡名称的字符串,值是 table 变量。而且我不确定这是最好的方法。
这是我现在尝试的方法:

var id = '#choice' + $("#tabs ul>li a").eq(tabs.tabs('option', 'active')).attr('href').slice(-1);
$(id).row.add( dialogTable.rows({ selected: true }).data() ).draw();

所以,即使我注释第一行并硬编码“#choice1”,它仍然会产生错误TypeError: $(...).row is undefined

您必须在 DataTables API 实例上调用 .row() 而不是 在 jQuery table 对象上。

调用.DataTable() 将初始化一个数据table 和return 一个API 实例。如果 table 已经初始化,它只会 return 实例。

From the docs:

Accessing the API

A new DataTables API instance can be obtained for one or more tables in one of three different ways:

  • $( selector ).DataTable();

  • $( selector ).dataTable().api();

  • new $.fn.dataTable.Api( selector );

The result from each is an instance of the DataTables API object which has the tables found by the selector in its context.

这将为您提供所需的行:

$(id).DataTable().row()

因此,这应该有效:

$(id).DataTable().row.add(dialogTable.rows({ selected: true}).data() ).draw();