乐趣区

关于layui:layui-table-表格动态表头列

从后端获取表头

function initTable() {
      $.ajax({
        url: "getList",
        method: "post",
        data: {...},
        success: function (res) {
          var cols = [
            {
              title: "No.",
              type: "numbers",
              fixed: "left",
              width: 40,
            },
          ];

          for (var i = 1, len = Object.keys(res.data[0]).length;
            i <= len;
            i++
          ) {// 创立闭包环境,避免变量援用谬误的问题
            (function (i) {
              var field = "key" + i;// 后端传来的表头属性名 key1,key2。。。var fieldObj = {
                field: field,
                title: res.data[0][field],
              };
              if (i > 1) {fieldObj.templet = function (d) {// 自定义数据模版
                  return (
                    "<div>" +
                    d[field] +
                    "</div>"
                  );
                };
              }
              cols.push(fieldObj);
            })(i);
          }

          res.data.shift(); // 删除表头项,渲染表格
          console.log(cols);
          layui.table({
            elem: "#tableid",
            height: '500',
            cols: [cols],
            data: res.data,
            limit: res.data.length,
          });
        },
        error: function (resp) {layer.msg(resp.msg);
        },
      });
退出移动版