我正在使用 DataTable 1.10.9(来自 https://datatables.net )。数据表的列在 javascript 的初始化步骤中定义,每列都有一个唯一的名称,例如:
var table = $('#example').DataTable({
columns: [
{ name: 'first-name' },
{ name: 'last-name' },
{ name: 'position' },
{ name: 'location' },
{ name: 'salary' }
]
});
我知道我可以通过给定的名称从表中获取列,但我似乎无法找到如何从列对象中查找列的名称。 (我希望在组件的当前状态下这是可能的。)例如:
table.columns().every(function() {
//I'd want to see what the name of this column is, something like:
console.log(this.name()); //will throw an exception since no such function exists
//or
console.log(this.name); //will output 'undefined'
});
获取名称的正确函数或属性是什么?
最佳答案
您可以通过 table.settings().init()
检索初始化选项- 由此columns
这样定义:
var columns = table.settings().init().columns;
单击单元格时/<td>
您可以通过以下方式找到列索引(隐藏列的最佳实践):
var colIndex = table.cell(this).index().column;
警告相应 column.name
的点击处理程序示例单击单元格时
$("#example").on('click', 'td', function() {
//get the initialization options
var columns = table.settings().init().columns;
//get the index of the clicked cell
var colIndex = table.cell(this).index().column;
alert('you clicked on the column with the name '+columns[colIndex].name);
})
您的every()
例子是
var columns = table.settings().init().columns;
table.columns().every(function(index) {
console.log(columns[index].name);
})
关于javascript - 如何获取数据表列的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32598279/