layui 表格动态添加行 完整代码
时间: 2023-11-15 12:47:38 浏览: 320
完整代码如下:
HTML:
```html
<table id="demo" lay-filter="test"></table>
<script type="text/html" id="toolbarDemo">
<div class="layui-btn-container">
<button class="layui-btn layui-btn-sm" lay-event="add">添加行</button>
</div>
</script>
```
JavaScript:
```javascript
layui.use('table', function(){
var table = layui.table;
//展示已知数据
var data = [{
"id": "10001",
"username": "张三",
"email": "zs@layui.com",
"sex": "男",
"city": "浙江杭州",
"sign": "人生就像是一场修行",
"experience": "116",
"ip": "192.168.0.8",
"logins": "108",
"joinTime": "2016-10-14"
}, {
"id": "10002",
"username": "李四",
"email": "ls@layui.com",
"sex": "女",
"city": "浙江温州",
"sign": "让天下没有难写的代码",
"experience": "12",
"ip": "192.168.0.8",
"logins": "106",
"joinTime": "2016-10-14"
}, {
"id": "10003",
"username": "王五",
"email": "ww@layui.com",
"sex": "女",
"city": "浙江宁波",
"sign": "码农,码出高质量",
"experience": "65",
"ip": "192.168.0.8",
"logins": "106",
"joinTime": "2016-10-14"
}, {
"id": "10004",
"username": "赵六",
"email": "z6@layui.com",
"sex": "男",
"city": "浙江杭州",
"sign": "我爱layui",
"experience": "666",
"ip": "192.168.0.8",
"logins": "106",
"joinTime": "2016-10-14"
}, {
"id": "10005",
"username": "周七",
"email": "z7@layui.com",
"sex": "男",
"city": "浙江义乌",
"sign": "浩浩荡荡,俱是翻滚的浪花",
"experience": "86",
"ip": "192.168.0.8",
"logins": "106",
"joinTime": "2016-10-14"
}];
table.render({
elem: '#demo',
toolbar: '#toolbarDemo',
cols: [[
{type:'checkbox'},
{field:'id', title:'ID', width:80},
{field:'username', title:'用户名', width:120},
{field:'email', title:'邮箱', minWidth:150},
{field:'sign', title:'签名'},
{field:'sex', title:'性别', width:80},
{field:'city', title:'城市'},
{field:'experience', title:'积分', width:80},
{field:'logins', title:'登入次数', width:100},
{field:'joinTime', title:'加入时间', width:120},
{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150}
]],
data: data,
page: true
});
//监听头部工具栏事件
table.on('toolbar(test)', function(obj){
var data = obj.data;
switch(obj.event){
case 'add':
var tableData = table.cache.demo;
var newRow = {
"id": "",
"username": "",
"email": "",
"sex": "",
"city": "",
"sign": "",
"experience": "",
"ip": "",
"logins": "",
"joinTime": ""
};
tableData.push(newRow);
table.reload('demo', {
data: tableData
}, 'data');
break;
};
});
});
```
在这个示例中,我们使用 layui 的表格组件,创建了一个包含多个固定列和可选操作的表格。我们还添加了一个头部工具栏,包含一个按钮,用于添加新的行。
当用户点击添加按钮时,我们使用 table.cache 方法获取当前表格的数据,然后创建一个新的空行(具有相同的字段),并将其添加到表格数据中。最后,我们使用 table.reload 方法重新加载表格,以显示新的行。
注意:在实际使用中,您需要根据您的需求更改表格字段和样式,以及添加其他可选操作。
阅读全文