[英]How to get name of datatable column?
我正在使用 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);
})
您可以嘗試使用另一種方法。 “指數”變量是你的THEAD列。 此方法將獲取表格的 thead 列並讀取標簽內的文本。
dataTable.column(index).header().textContent
下面的代碼對我有用
this.api().columns().every(function() {
console.log( this.header().textContent )
})
您也可以為特定的列名稱添加特定的 html 類,例如擁有該類
this.api().columns(".myColumnClass").every(function() {
console.log( this.header().textContent )
})
文檔顯示columns().every()
this
設置為當前列的column()
對象。 對列對象的進一步檢查表明它有一個column().data()
方法,該方法將列包含的數據作為值數組返回。 這應該提供您需要的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.