html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>表格列动态隐藏示例</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/layui/2.5.6/css/layui.min.css">
<script src="https://cdn.staticfile.org/jquery/3.0.0/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/layui/2.5.6/layui.min.js"></script>
</head>
<body>
<button id="btn">隐藏状态列</button>
<table id="test" lay-filter="test"></table>
<script>
layui.use(['table', 'layer'], function(){
var table = layui.table;
var layer = layui.layer;
// 定义表格
table.render({
elem: '#test',
cols: [[
{field:'id', title:'ID', width:80},
{field:'username', title:'用户名', width:120},
{field:'email', title:'邮箱', minWidth:150},
{field:'sex', title:'性别', width:80},
{field:'city', title:'城市', width:100},
{field:'sign', title:'签名', minWidth: 150},
{field:'experience', title:'积分', width: 80, sort: true},
{field:'score', title:'评分', width: 80, sort: true},
{field:'classify', title:'职业', width: 100},
{field:'wealth', title:'财富', width: 135, sort: true},
{field:'status', title:'状态', width: 100}
]],
data: [{
id: 1,
username: 'user1',
email: 'user1@test.com',
sex: '男',
city: '北京',
sign: '我是个程序员',
experience: 123,
score: 76,
classify: '工程师',
wealth: 9999,
status: '正常'
}, {
id: 2,
username: 'user2',
email: 'user2@test.com',
sex: '女',
city: '上海',
sign: '我是个产品经理',
experience: 456,
score: 23,
classify: '产品',
wealth: 8888,
status: '异常'
}],
page: true
});
// 点击按钮隐藏状态列
$('#btn').click(function() {
$.ajax({
url: '/api/test',
success: function(res) {
if (res.status === 'ok') {
// 根据应答结果动态设置要隐藏的列
layui.each(table.config.cols[0], function(index, item) {
if (item.field === 'status') {
table.config.cols[0][index].hide = true;
return false;
}
});
// 重新加载表格
table.reload('test', {
page: {curr: 1} // 设置当前页码为第一页
});
} else {
layer.msg('隐藏状态列失败!');
}
},
error: function() {
layer.msg('隐藏状态列出错!');
}
});
});
});
</script>
</body>
</html>
在这个例子中,我们定义了一个表格,并在表格中展示了一些基本数据。当点击按钮时向服务器发送一个异步请求,接收到应答结果后根据应答结果动态隐藏表格中的状态列,并重新加载表格,以便实现动态隐藏效果。