如何获取datatable列的名称? [英] How to get name of datatable column?
问题描述
我正在使用DataTable 1.10.9(来自 https://datatables.net )。数据表的列在javascript的初始化步骤中定义,每列都有唯一的名称,例如:
I'm using DataTable 1.10.9 (from https://datatables.net). Columns for the datatable are defined at the initialization step in javascript and each column has a unique name, e.g.:
var table = $('#example').DataTable({
columns: [
{ name: 'first-name' },
{ name: 'last-name' },
{ name: 'position' },
{ name: 'location' },
{ name: 'salary' }
]
});
我知道我可以通过我给它的名字从表中获取列,但是我似乎无法找到如何从列对象中查找列的名称。 (我希望它可以用于组件的当前状态。)例如:
I know I can get the column from the table by the name I've given it, but I can't seem to find how to find a column's name from the column object. (I'm hoping it's possible with the current state of the component.) For example:
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'
});
获取名称的正确功能或属性是什么?
What's the proper function or property to get the name there?
推荐答案
您可以通过 table.settings()。init()
检索初始化选项 - 并且 columns
这样定义:
You can retrieve the initialization options through table.settings().init()
- and by that the columns
definition this way :
var columns = table.settings().init().columns;
点击单元格/ < td>
你可以找到列索引(隐藏列的最佳实践):
When clicking on a cell / <td>
you can find the column index by (best practice in case of hidden columns) :
var colIndex = table.cell(this).index().column;
一个点击处理程序示例,提醒相应的 column.name
单击单元格时
An example of a click handler that alerts the corresponding column.name
when a cell is clicked
$("#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);
})
演示 - > http:// jsfiddle.net/6fstLmb6/
demo -> http://jsfiddle.net/6fstLmb6/
这篇关于如何获取datatable列的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!