layui数据表格,Switch按钮点击后修改表单数据

layui是一个很好的前端模板,但是个人觉得写的教程不太友好,不适合初学者(像我这样的菜鸟)

最近在写一个数据表格,官方是这样展示的
在这里插入图片描述

<script type="text/html" id="switchTpl">
  <!-- 这里的 checked 的状态只是演示 -->
  <input type="checkbox" name="sex" value="{
   
   {d.id}}" lay-skin="switch" lay-text="女|男" lay-filter="sexDemo" {
   
   { d.id == 10003 ? 'checked' : '' }}>
</script>


<script>
layui.use('table', function(){
  var table = layui.table
  ,form = layui.form;
  
  table.render({
    elem: '#test'
    ,url:'/static/json/table/user.json'
    ,cellMinWidth: 80
    ,cols: [[
      {type:'numbers'}
      ,{type: 'checkbox'}
      ,{field:'id', title:'ID', width:100, unresize: true, sort: true}
      ,{field:'username', title:'用户名', templet: '#usernameTpl'}
      ,{field:'city', title:'城市'}
      ,{field:'words', title: '字数', minWidth:120, sort: true}
      ,{field:'sex', title:'性别', width:85, templet: '#switchTpl', unresize: true}
      ,{field:'lock', title:'是否锁定', width:110, templet: '#checkboxTpl', unresize: true}
    ]]
    ,page: true
  });
  
  //性别操作
  form.on('switch(sexDemo)', function(obj){
    layer.tips(this.value + ' ' + this.name + ':'+ obj.elem.checked, obj.othis);
  });

看完官方文档,表示一脸懵逼……

下面的我的代码

//数据表格关键代码
 {field: 'isfree', title: '是否收费', event:'isfree',width:100,templet:function (res) {
                            let menuId = res.id;//当前行ID
                            if (res.isfree == 0){
                                return "<input type='checkbox'  id = '" + menuId + "' name='isfree' value='0' lay-filter='isfree' lay-skin='switch' lay-text='收费|免费' checked>"
                            }else {
                                return "<input type='checkbox'  id = '" + menuId + "' name='isfree' value='1' lay-filter='isfree' lay-skin='switch' lay-text='收费|免费'>"
                            }
                        }, unresize: true}

templet后面:写的是自定义显示的内容,我加上个判断方法,用于显示滑块的状态
在这里插入图片描述
res:里面是点击表格对象,里面有当前input的value值,可以通过它获取到Switch的值

点击按钮后,里面的值应该也发生改变,可以通过以下代码来实现

table.on('tool(product_table)', function (obj) {
var data = obj.data;
if (obj.event === 'isfree') {
                    if (obj.data.isfree == 1) {
                        //如果原本的值收费1,则修改值为0
                        obj.update({
                            isfree: 0
                        });
                    } else {
                        //如果原本免费0,则修改值为1
                        obj.update({
                            isfree: 1
                        });
                    }
                }

obj.data是选中行的所有内容
obj.update方法可以修改更新table。{}里面的需要更新的字段值

猜你喜欢

转载自blog.csdn.net/weixin_41717861/article/details/126917803