我在这个链接中使用Datatable来显示一个网格。https://datatables.net/examples/basic_init/hidden_columns.html
我使用(columnDefs.targets)显示成对的默认列,然后我添加了在此链接中显示和隐藏列的功能:
https://datatables.net/examples/api/show_hide.html
首先我加载的页面是正确的,并显示默认的列,当我尝试显示/隐藏时,它显示所有的列而不是默认的一列,我不确定如何只显示默认的一列。
这是我的代码:
$(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);
});
});
});发布于 2015-12-01 03:46:40
你有没有试过存储目标列表?
那么只更新每个函数中的列表吗?像这样的东西?
$(document).ready(function () {
var targetArr = [4,5,6,7,8,9,10,14,15,16,17,18,19,20,21,22,23,24,25,26,27];
var table = $('#DataLegal').DataTable({
"columnDefs": [{
"targets": targetArr,
"visible": false
// "searchable": false
}]
});
$(ms).on('selectionchange', function(e,m){
// Turn on columns
$.each(table.columns()[0], function(index) {
if($.inArray(item, targetArr)){
table.column(item).visible(true); //in case some values were false set all to true
} else {
table.column(item).visible(false);//in case some values were true set all to false
}
});
$.each(this.getValue(), function(index, item) {
table.column(item).visible(false);
});
});
});发布于 2015-12-01 04:14:39
您可以通过table.init().columnDefs解压columnDefs设置,
table.init().columnDefs[0].targets将返回上面的[ 4,5,6,7,8,9,10,14,15,16...]数组。创建包含隐藏列的值的显示/隐藏选择框的一种快捷方法是
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>');
}) 当用户在选择框中选择列时显示/隐藏列
$("#columns").on('change', function() {
table.column(this.value).visible(!table.column(this.value).visible())
}) 演示->
https://stackoverflow.com/questions/34006473
复制相似问题