问题描述
我在此链接中使用 Datatable 来显示网格.https://datatables.net/examples/basic_init/hidden_columns.html
I am using Datatable in this link to show a grid.https://datatables.net/examples/basic_init/hidden_columns.html
我使用 (columnDefs.targets) 显示几个默认列,然后我添加了从此链接显示和隐藏列的功能:
I show couple default column using (columnDefs.targets) then I have added the ability to show and hide the column from this link:
https://datatables.net/examples/api/show_hide.html
首先我加载页面是正确的并显示默认列,当我尝试显示/隐藏时,它显示所有列而不是默认列,我不确定如何在那里只显示默认列.
first I load the page is correct and shows the default columns, when I try to show/hide , it show all the column instead of default one, I am not sure how to show only default one there.
这是我的代码:
$(document).ready(function () {
var table = $('#DataLegal').DataTable({
"columnDefs": [
{
"targets": [ 4,5,6,7,8,9,10,14,15,16,17,18,19,20,21,22,23,24,25,26,27],
"visible": false
// "searchable": false
}
]
} );
//This is show/Hide part
var ms = $('#magicsuggest').magicSuggest({
// Converts our C# object in a JSON string.
data: @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(columns))
});
$(ms).on('selectionchange', function(e,m){
// Turn on columns
$.each(table.columns()[0], function(index) {
table.column(index).visible(true);
//here how I can only turned on the DefColumns?
});
// Turn off each column in the value array... Value = int[0,1, 2, ...]
$.each(this.getValue(), function(index, item) {
table.column(item).visible(false);
});
});
});
推荐答案
您可以通过 table.init().columnDefs
,
table.init().columnDefs[0].targets
将返回上面的 [ 4,5,6,7,8,9,10,14,15,16...]
数组.一种创建显示/隐藏选择框的快速方法来保存隐藏列的值可能是
will return the above [ 4,5,6,7,8,9,10,14,15,16...]
array. A quick way to create a show / hide select box holding values of the hidden columns could be
show / hide column :<select id="columns"></select>
填充隐藏列
table.init().columnDefs[0].targets.forEach(function(column) {
$("#columns").append('<option value="'+column+'">show / hide column #'+column+'</option>');
})
当用户在选择框中选择一列时显示/隐藏列
show / hide columns when the user select a column in the select box
$("#columns").on('change', function() {
table.column(this.value).visible(!table.column(this.value).visible())
})
演示 -> http://jsfiddle.net/dwhwftxc/
demo -> http://jsfiddle.net/dwhwftxc/
这篇关于如何在 jquery DataTable 中打开 columnDefs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!