layui 动态列,splice首行添加,push尾部添加

本文介绍了一种在前端动态表格中添加首部复选框和尾部操作列的方法。首先,从后端获取数据ColsList,然后通过JavaScript的Array方法`splice`在数据首部插入复选框列,再使用`push`方法在尾部添加操作列,包含编辑和删除按钮。最后,将处理后的数据传递给layui表格组件,实现了动态列展示及操作功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,目标代码


 cols: [
        [
           {type: 'checkbox'},
           {field: 'name', title: '标题',  width:110,  align: 'center', halign: 'center'},
           {field: 'name', title: '标题',  width:110,  align: 'center', halign: 'center'},
           {field: 'name', title: '标题',  width:110,  align: 'center', halign: 'center'},
           {field: 'name', title: '标题',  width:110,  align: 'center', halign: 'center'},
           {field: 'name', title: '标题',  width:110,  align: 'center', halign: 'center'},
           {field: 'operate', title: '操作', align: 'center', width: 100,  templet: function(d){
               return '<a style="color: #409EFF;" lay-event="edit">修改</a>' +
                   '<a style="color: #409EFF;margin-left: 10px" lay-event="del">删除</a>'
           }}
         ]
   ],
            


2,现有的动态数据

从后端传来的数据 ColsList 只有中间这段


   {field: 'name', title: '标题',  width:110,  align: 'center', halign: 'center'},
   {field: 'name', title: '标题',  width:110,  align: 'center', halign: 'center'},
   {field: 'name', title: '标题',  width:110,  align: 'center', halign: 'center'},
   {field: 'name', title: '标题',  width:110,  align: 'center', halign: 'center'},
   {field: 'name', title: '标题',  width:110,  align: 'center', halign: 'center'},
        

3,前端组合

首部添加


 {type: 'checkbox'}

尾部添加


 {field: 'operate', title: '操作', align: 'center', width: 100,  templet: function(d){
     return '<a style="color: #409EFF;" lay-event="edit">修改</a>' +
            '<a style="color: #409EFF;margin-left: 10px" lay-event="del">删除</a>'
 }}

最终代码:


  //初始化
 var ColsList= ${ColsList};
  //首部添加
 ColsList.splice(0,0,{type: 'checkbox'})  
 //尾部添加
 ColsList.push({field: 'operate', title: '操作', align: 'center', width: 100,  templet: function(d){
        return '<a style="color: #409EFF;" lay-event="edit">修改</a>' +
               '<a style="color: #409EFF;margin-left: 10px" lay-event="del">删除</a>'
 }});  

//最后放入layui的表格属性中
 cols: [
  		 ColsList
       ],
        

4,知识笔记

4.1,splice

语法:

// 索引从0开始计数

arrayObject.splice(索引,删除项目数量,添加新项目1,…,添加新项目n)

4.2,push

语法:

arrayObject.push(添加新项目1,…,添加新项目n)

push() 方法可把它的参数顺序添加到 arrayObject 的尾部。它直接修改 arrayObject,而不是创建一个新的数组。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值