1 在HTML文件中添加一个div标签,设置id为test,该div用于放置表格。
<div id="test"></div>2 在JS文件中使用table.render方法创建一个表格,定义表头和数据等参数。
table.render({
elem: '#test',
cols: [[
{field: 'id', title: 'ID', width: 80},
{field: 'username', title: '用户名', width: 120},
{field: 'email', title: '邮箱', minWidth: 200},
{field: 'operation', title: '操作', width: 120, templet: '#operationTpl'}
]],
data: [
{id: 1, username: '张三', email: 'zhangsan@qq.com'},
{id: 2, username: '李四', email: 'lisi@qq.com'},
{id: 3, username: '王五', email: 'wangwu@qq.com'}
]
});
3 在HTML文件中添加一个script标签,定义添加一行按钮和删除一行按钮的模板。
<script type="text/html" id="operationTpl">
<button class="layui-btn layui-btn-xs" lay-event="add">添加一行</button>
<button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除本行</button>
</script>4 在JS文件中使用table.on方法监听操作按钮的点击事件,实现添加一行和删除一行的功能。
table.on('tool(test)', function(obj){
var data = obj.data;
if(obj.event === 'add'){
table.addRow('#test', {
id: '',
username: '',
email: ''
});
} else if(obj.event === 'delete'){
layer.confirm('确定要删除这一行吗?', function(index){
obj.del();
layer.close(index);
});
}
});
5 在上面的代码中,我们使用了table.addRow方法添加一行数据,并使用layer.confirm方法弹出确认框来提示用户是否确定要删除一行数据。
6 最后,记得引入layui的CSS文件,否则样式可能会错乱。
<link rel="stylesheet" href="layui/css/layui.css">
评论区