layui--table里使用switch

1. 项目需求

layui.table上面渲染后的列表上面加一个switch开关,监听switch开关的动作,实现本列数据的状态切换!
实现效果如下:
在这里插入图片描述

2. 实现方式

下面介绍的思路都是利用tabletemplet模板实现的,不同的在于模板代码。
表格配置参数:

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}
    ]]
  });
方式一
<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>
方式二
<script type="text/html" id="statusTemp">
{{#  if(d.media.status==1){ }}
    <input type="checkbox" name="status" lay-skin="switch" checked   lay-text="开启|关闭"  value= {{ d.media.id}}  lay-filter="status" >
{{#  } else { }}
    <input type="checkbox" name="status" lay-skin="switch"  lay-text="开启|关闭"  value= {{ d.media.id} lay-filter="status" >
{{#  } }}
方式三
, {field: 'is_not_use', title: '状态', width: 130,templet: function(d){  //自定义显示内容
      var strCheck = d.is_not_use == "0" ? "checked" : "";
       return '<input type="checkbox" name="status" lay-filter="status" lay-skin="switch" lay-text="可用|禁用" ' +strCheck+ ' mid='+d.id+'>';
}}
3. JS监听
  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);
		}
	});
  });

上面介绍了两种获取行数据的ID方式,但是都需要原生js去遍历table数据,对于前端操作可能影响加载。
介绍个投机取巧的方式:
因为switch的开关状态由obj.elem.checked获取,所以可以将templetinput value值绑定成行数据ID,这样可以利用obj.value就可以获取行Id了。也就是将实现方式里面的value绑定数据改一下,例如改成d.id即可。

上一篇:Oracle解析exp、imp及常见的问题


下一篇:基于Zookeeper 简单实现分布式任务协调组件