jquery - How to iterate through all column headers in jQuery Datatables
问题描述
I am using a "fnDrawCallback" in Datatables to get the all column headers names () for that I am using the code below
"fnDrawCallback": function () {
table.column().every( function () {
var data = this.data();
var title = table.columns().header();
console.log($(title).html());
} );
I can get the column header name for first column . I want to know how can I iterate through all columns in table and get all the header () name?
解决方案
The simplest way I know to do this is with some jQuery inside the drawCallback
option:
<script type="text/javascript">
$(document).ready(function() {
$('#example').DataTable( {
"drawCallback": function ( settings ) {
$('#example thead tr th').each(function() {
console.log( $(this).html() );
});
}
} );
} );
</script>
I am using the more recent drawCallback
, not the older legacy fnDrawCallback
(but both do work).
Just to note: In your question, you are using table.column().every( function () {...}
. I can't see how you are defining your table
variable, in your example. So if my suggested approach is not suitable, perhaps you can edit your question to show the context in which you are using fnDrawCallback
.
Update
If you want to hide one or more columns based on the names of the column headings, then you can take the above code and modify it as follows:
<script type="text/javascript">
$(document).ready(function() {
$('#example').DataTable( {
"drawCallback": function ( settings ) {
var tbl = $('#example').DataTable();
var colIndex = 0;
$('#example thead tr th').each(function() {
var colHeading = $(this).html();
if (colHeading === 'Office' || colHeading === 'Age') {
tbl.columns( colIndex ).visible( false );
}
colIndex += 1;
});
}
} );
} );
</script>
In the above example, I have a table where the "Office" and "Age" columns are hidden when the table is drawn.
推荐阅读
- python - 检查列表中的多个值
- ios - 自定义条码扫描器,无法传回扫描数据
- c# - 如何将 xml 文件转换为字符串,同时保留标签并用值填充其中包含的一些元素?
- python - Pandas DataFrame 根据列表中指定名称的多个列的值选择行
- django - 按然后循环分组
- c - SDL_SetColorKey() 没有删除背景颜色
- postgresql-9.5 - 使用带有 IN 语句的 ILIKE 选择查询
- google-apps-script - 无法终止函数(> 500 000 次执行)
- docker - 在使用 Hyperledger Composer 构建的 Hyperledger Fabric 网络上配置 Kafka 排序服务
- ios - 线程 1:在 TableView Swift 上重新加载数据时,在 AppDelegate 上发出 SIGABRT 信号