layui table 上面的switch開關切換,並獲取表格里所有數據


layui table 上面的switch開關切換,並獲取表格里所有數據

場景需求:

在layui.table上面渲染后的列表上面加一個switch開關,監聽switch開關的動作,實現本列數據的狀態切換!

配圖:

 

 數據表格配置參數 layui.table.options.cols 配置如下、重點看 state 那一行

table.render({
    elem: '#demo'
    ,height: 312
    ,url: '/demo/table/user/' //數據接口
    ,page: true //開啟分頁
    ,cols: [[ //表頭
      {field: 'id', title: 'ID', width:80, sort: true, fixed: 'left'}
      ,{field: 'username', title: '用戶名', width:80}
      ,{field: 'sex', title: '性別', width:80, sort: true}
      ,{field:'state', title:'啟用狀態', width:80,templet:"#switchTpl"}
      ,{field: 'city', title: '城市', width:80} 
      ,{field: 'sign', title: '簽名', width: 177}
      ,{field: 'experience', title: '積分', width: 80, sort: true}
      ,{field: 'score', title: '評分', width: 80, sort: true}
      ,{field: 'classify', title: '職業', width: 80}
      ,{field: 'wealth', title: '財富', width: 135, sort: true}
    ]]
  });

switchTpl代碼段:

<script id="switchTpl" type="text/html">
    <input type="checkbox"  name="state"  value = {{d.state}} lay-skin="switch" lay-text="開啟|關閉" lay-filter="state" {{ d.state == '0' ? 'checked' : '' }}>
</script>

再寫一段JS,監聽switch的選中事件

  form.on('switch(state)', function(obj){
    //根據業務判斷是開啟還是關閉
    var state = obj.elem.checked?0:1;
    //方法一取數據(根據相對位置取)
    var id = obj.othis.parents('tr').find("td :first").text();
    //方法二取數據 (根據索引table.cache里面的行數據)
    var index  = obj.othis.parents('tr').attr("data-index");
    var id = tableData[index].id;
        
    $.get("/demo/table/user/",{"id":id,"state":state},function (res) {
        if(res.code != '0'){
            layer.msg(res.msg);
        }
    });
  });

如果需要的數據在列表上顯示,可以直接用方法一,如果不在則可以用方法二取數據;

上面代碼中的tableData 為事先定義好的對象

var tableData;

該參數在 table.render 的時候賦值(在上面的table.render方法參數里面,再加上這兩句賦值):

,id:"tableIns"
,done:function(){
    tableData = table.cache.tableIns;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM