在DataTable 1.10中动态显示/隐藏列 [英] Dynamically show/hide columns in DataTables 1.10

查看:497
本文介绍了在DataTable 1.10中动态显示/隐藏列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过使用DataTables主页的示例部分的代码实现动态隐藏/显示在复选框(onChange事件)上。

Im trying to implement dynamically hide/show on a checkbox (onChange event) using code the example section of the DataTables homepage.

function(e){
    //e.preventDefault();
    console.log($(this).attr('datacolumn'));

    // Get the column API object
    var column = table.column($(this).attr('datacolumn'));

    // Toggle the visibility
    column.visible( ! column.visible() );
}

但是我收到错误。它表示table.column是undefined

However I get an error. It says table.column is "undefined"

未捕获TypeError:undefined不是一个函数

Uncaught TypeError: undefined is not a function

尝试更改表变量的范围,以便我在Chrome的控制台中与其进行交互。只要我能看到它只是指向一个html内容。

I've tried changing the scope of the table-variable in order for me to interact with it in the console of Chrome. And as far as I can see it just points to a htmlcontent.

更新

当我指定对象的完整路径时,它工作。

It worked when I specified the complete path to the object.

var column = $('#example').dataTable().api().column($(this).attr('datacolumn'))


推荐答案

此外,这里是一个非常简单的脚本
,以动态添加切换按钮,基于表的内容
在表顶部的
和绑定一个点击以切换每个

in addition, here is a very simple script to dynamically add toggle buttons based on table thead content in a div on top of the table and bind a click to toggle visibility for each

$(document).ready(function() {
var table = $('#example').DataTable();
	
	// for each column in header add a togglevis button in the div
	$("#example thead th").each( function ( i ) {
		var name = table.column( i ).header();
		var spanelt = document.createElement( "button" );
		spanelt.innerHTML = name.innerHTML;						
		
		$(spanelt).addClass("colvistoggle");
		$(spanelt).attr("colidx",i);		// store the column idx on the button
		
		$(spanelt).on( 'click', function (e) {
			e.preventDefault(); 
			// Get the column API object
			var column = table.column( $(this).attr('colidx') );
			 // Toggle the visibility
			column.visible( ! column.visible() );
		});
		$("#colvis").append($(spanelt));
	});
} );

<div id="colvis"></div>
<table id="example" class="display" cellspacing="0" width="100%">
  <thead>
    <!-- here your col header -->
    </thead>
  <tbody>
  <!-- here your table data -->
  </tbody>
</table>

这篇关于在DataTable 1.10中动态显示/隐藏列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆