如何设置DataTables首次加载时仅显示指定列(如Office info)
How to Default to "Office info" Columns on Initial Load in DataTables
Got it, let's fix this up! You want your DataTable to load with only the "Office info" columns visible right off the bat, instead of showing all columns first. Here's exactly how to adjust your existing code to make that happen:
Modified Code
$(document).ready(function() { $('#example').DataTable({ dom: 'Bfrtip', // Set default hidden columns to match the "Office info" group columnDefs: [ { targets: [3, 4, 5], visible: false } ], buttons: [ { extend: 'colvisGroup', text: 'Office info', show: [1, 2], hide: [3, 4, 5] }, { extend: 'colvisGroup', text: 'HR info', show: [3, 4, 5], hide: [1, 2] } ] }); });
What's Changed & Why
- We added the
columnDefsoption to define the initial visibility of columns. Thetargets: [3,4,5]targets the columns you want hidden by default, andvisible: falseensures they're not shown when the page loads. This matches exactly which columns the "Office info" group is set to hide. - Your existing
colvisGroupbuttons work exactly as before: clicking "HR info" will switch to showing those columns, and clicking "Office info" will toggle back (though it'll already be active on load).
Quick Note About Column Indexes
Remember that DataTables uses 0-based indexing for columns by default. If your actual column order is different (e.g., if the first column in your table is index 0 instead of 1), just adjust the numbers in targets, show, and hide to match your real column positions.
内容的提问来源于stack exchange,提问作者HattrickNZ
相关产品推荐
相关产品推荐

