LayUIでテーブルから選択されたデータを取得する方法は何ですか?
Layuiでは、テーブルのチェックボックスの変更イベントを監視することで、テーブルで選択されたデータを取得できます。具体的な手順は以下の通りです。
- 表格のチェックボックス選択ボックスに「lay-filter」属性を追加し、その選択ボックスの名前を識別するために使用します。例えば、「lay-filter=”check”」。
- JavaScriptコード内で、layuiのformモジュールを使用してcheckboxの変更イベントを監視します。
- changeイベントのコールバック関数内で、layuiのtableモジュールのcheckStatusメソッドを使用して、テーブルで選択されたデータを取得することができます。
以下はサンプルコードです。
HTMLコード:
<table class="layui-table">
<thead>
<tr>
<th><input type="checkbox" lay-filter="check" /></th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" lay-filter="check" /></td>
<td>张三</td>
<td>20</td>
<td>男</td>
</tr>
<tr>
<td><input type="checkbox" lay-filter="check" /></td>
<td>李四</td>
<td>22</td>
<td>女</td>
</tr>
</tbody>
</table>
JavaScriptのコード:
layui.use(['form', 'table'], function() {
var form = layui.form;
var table = layui.table;
// 监听checkbox选择框的change事件
form.on('checkbox(check)', function(data) {
// 获取表格选中的数据
var checkStatus = table.checkStatus('tableId'); // tableId为表格的id
var data = checkStatus.data; // 获取选中的数据
console.log(data);
});
});
上記のコードでは、選択ボックスの状態が変更されると、changeイベントのコールバック関数がトリガーされます。このコールバック関数では、table.checkStatusメソッドを使用して表の選択されたデータを取得し、それをコンソールに出力します。