Layui 表格:获取选中行数据并操作
Layui 表格:获取选中行数据并操作
本文将介绍如何使用 Layui 表格组件获取选中行数据,并通过按钮点击事件将数据传递到后端进行处理。
1. 添加行选中事件
首先,需要给表格添加行选中事件。可以使用 table.on('row(table)', function (obj) {}) 方法,其中 table 是表格的 lay-filter 属性值,obj 为事件对象,包含了选中行的数据对象 data。
table.on('row(table)', function (obj) {
// obj.data 即为选中行的数据对象
});
2. 获取选中行数据
在按钮点击事件中,可以使用 table.checkStatus('table').data 方法获取选中行数据,table 是表格的 lay-filter 属性值。该方法返回一个数组,包含所有选中行的数据对象。
var table = layui.table;
// 获取选中行数据
var selectedData = table.checkStatus('table').data;
// 处理选中行数据
// ...
3. 将数据传递到后端
可以通过 AJAX 请求将选中行数据传递到后端进行处理。例如,可以使用 jQuery 的 $.post() 方法:
$.post('/api/save-data', {
data: selectedData
}, function (res) {
// 处理返回结果
});
其中,/api/save-data 是后端接口地址,selectedData 是选中行数据数组。
示例代码
<table class="layui-table" lay-filter="table">
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr>
<td>张三</td>
<td>20</td>
</tr>
<tr>
<td>李四</td>
<td>25</td>
</tr>
</tbody>
</table>
<button class="layui-btn" id="saveBtn">保存</button>
<script>
layui.use(['table'], function() {
var table = layui.table;
table.on('row(table)', function(obj) {
console.log(obj.data);
});
$('#saveBtn').click(function() {
var selectedData = table.checkStatus('table').data;
$.post('/api/save-data', {
data: selectedData
}, function(res) {
console.log(res);
});
});
});
</script>
通过以上步骤,你就可以轻松地获取 Layui 表格中的选中行数据,并将其传递到后端进行处理。
原文地址: https://www.cveoy.top/t/topic/lCA3 著作权归作者所有。请勿转载和采集!