layui表格資料操作及事件繫結模板
阿新 • • 發佈:2022-03-01
點選檢視程式碼
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <title>layui 除錯預覽</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/layui/2.6.7/css/layui.css" media="all"> </head> <body> <script type="text/html" id="barDemo"> <a class="layui-btn layui-btn-xs" lay-event="detail">檢視</a> <a class="layui-btn layui-btn-xs" lay-event="edit">編輯</a> <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">刪除</a> </script> <table id="baseTable" class="layui-hide" lay-filter="test"> </table> <script src="https://cdnjs.cloudflare.com/ajax/libs/layui/2.6.7/layui.js"></script> <script> var data = [{"id":"1","day":"12.30","time":"12:30"},{"id":"2","day":"12.31","time":"11:30"}]; //載入模組 layui.use(function(){ //亦可載入特定模組:layui.use(['layer', 'laydate', function(){ //得到各種內建元件 var layer = layui.layer //彈層 ,laypage = layui.laypage //分頁 ,laydate = layui.laydate //日期 ,table = layui.table //表格 ,carousel = layui.carousel //輪播 ,upload = layui.upload //上傳 ,element = layui.element //元素操作 ,slider = layui.slider //滑塊 ,dropdown = layui.dropdown //下拉選單 //監聽Tab切換 element.on('tab(baseTable)', function(data){ layer.tips('切換了 '+ data.index +':'+ this.innerHTML, this, { tips: 1 }); }); //執行一個 table 例項 table.render({ elem: '#baseTable' ,height: 600 ,data: data ,title: 'test' ,page: true //開啟分頁 ,toolbar: '#toolbarDemo'//'default' //開啟工具欄,此處顯示預設圖示,可以自定義模板,詳見文件 ,totalRow: true //開啟合計行 ,cols: [[ //表頭 {type: 'checkbox', fixed: 'left'} ,{field: 'id', title: 'ID', width:80, type:'numbers', sort: true,align: "center"} ,{field: 'username', title: '使用者名稱', width:80,align: "center"} ,{field: 'experience', title: '積分', width: 90, sort: true,align: "center"} ,{field: 'sex', title: '性別', width:80, sort: true,align: "center"} ,{field: 'score', title: '評分', width: 80, sort: true,align: "center"} ,{field: 'city', title: '城市', width:150,align: "center"} ,{field: 'sign', title: '簽名', width: 200,align: "center"} ,{field: 'day', title: '職業', width: 100,align: "center"} ,{field: 'time', title: '財富', width: 135, sort: true,align: "center"} ,{fixed: 'right', id:'id', width: 200, align:'center', title:"操作", toolbar: '#barDemo',align: "center"} ]] }); //監聽工具條 table.on('tool(test)', function(obj){ //注:tool是工具條事件名,test是table原始容器的屬性 lay-filter="對應的值" var data = obj.data; //獲得當前行資料 var layEvent = obj.event; //獲得 lay-event 對應的值(也可以是表頭的 event 引數對應的值) var tr = obj.tr; //獲得當前行 tr 的DOM物件 if(layEvent === 'detail'){ //檢視 //do somehing alert('do!'); } else if(layEvent === 'del'){ //刪除 layer.confirm('真的刪除行麼', function(index){ layer.close(index); //向服務端傳送刪除指令 check(document.getElementById('id')); }); } else if(layEvent === 'edit'){ //編輯 alert('edit');} }); }); function check(id){ if(id = 1){ alert('刪除成功!'); }else{ alert('刪除失敗!') } } </script> </body> </html>