重新又封装下layui table 做个记录

本次封装实现了一个页面多次使用表格

直接上代码

例子代码


<div class="layui-fluid">

    <div class="layui-card">

        <div class="layui-card-body">

            <table class="layui-table" id="tableAdminlog" lay-filter="tableAdminlog"></table>

        </div>

    </div>

</div>



<script type="text/html" id="tablelinebar">

    <a class="layui-btn layui-btn-xs layui-bg-blue" lay-event="view">查看</a>

    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>

</script>



<script type="text/html" id="tabletoolbar">

    <div class="layui-btn-container">

        <button class="layui-btn layui-btn-sm" lay-event="refresh"><i class="layui-icon layui-icon-refresh"></i></button>

        <button class="layui-btn layui-btn-sm layui-bg-red" lay-event="del">删除</button>

    </div>

</script>



<script type="text/html" id="modelView">

    <div id="modelViewDiv" class="layui-card-body">

        <table class="layui-table" lay-even lay-skin="nob" style="word-break: break-all;

word-wrap: break-word;

    border-collapse: collapse;">

            <thead>

            <tr>

                <th width="100">标题</th>

                <th>内容</th>

            </tr>

            </thead>

            <tbody>

            <tr>

                <td>id</td>

                <td>{{ d.id }}</td>

            </tr>

            <tr>

                <td>admin_id</td>

                <td>{{ d.admin_id }}</td>

            </tr>

            <tr>

                <td>用户名</td>

                <td>{{ d.username }}</td>

            </tr>

            <tr>

                <td>url</td>

                <td>{{ d.url }}</td>

            </tr>

            <tr>

                <td>标题</td>

                <td>{{ d.title }}</td>

            </tr>

            <tr>

                <td>内容</td>

                <td>{{ d.content }}</td>

            </tr>

            <tr>

                <td>ip</td>

                <td>{{ d.ip }}</td>

            </tr>

            <tr>

                <td>useragent</td>

                <td>{{ d.useragent }}</td>

            </tr>

            <tr>

                <td>createtime</td>

                <td>{{ d.createtime }}</td>

            </tr>

            </tbody>

        </table>

        <div class="layui-form-item text-right">

            <button class="layui-btn layui-btn-primary" type="button" ew-event="closePageDialog">关闭</button>

        </div>

    </div>

</script>



<script>

    layui.use(['layer','laytpl', 'atable', 'admin'], function () {

        var $ = layui.jquery;

        var layer = layui.layer;

        var atable = layui.atable;

        var laytpl = layui.laytpl;

        //表头

        var cols= [[

            {type: 'checkbox', fixed: 'left'},

            {field: 'id',  title: 'ID',width:75,align:'center'},

            {field: 'username',  title: '账号',width:120},

            {field: 'title',  title: '标题'},

            {field: 'url', title: '访问地址'},

            {field: 'ip',  title: 'IP',width:140},

            {field: 'createtime',  title: '时间',width:175},

            {align: 'center', toolbar: '#tablelinebar', title: '操作', width: 150}

]];

        window.tt=insTb = atable.render(

{

                elem:'#tableAdminlog'

                , id:'tableAdminlog'

                , checkbox : true

                , defaultToolbar: ['filter']

                ,url:'{:url("")}'

                ,toolbar:"#tabletoolbar"

                ,cols:cols

                ,limit: 15

                ,page:true

                ,listen:{

                    //单击事件

                    click:function (obj) {

},

                    //双击事件

                    double:function (obj) {

                        var data = obj.data;

                        showDetailModel(data);

},

                    //单元格工具栏

                    tool:function (obj,event) {

                        var data = obj.data;

                        switch (event) {

                            case 'view':

                                showDetailModel(data);

                                break;

                            case 'del':

                                doDel(data.id);

                                break;

}

},

                    //表格工具栏

                    toolbar:function (obj,event) {

                        switch (event) {

                            case 'del':

                                var id = insTb.getMany();

                                console.log(id);

                                if (id != null) {

                                    doDel(id);

}

                                break;

}

}

}

}

);

        // 删除

        function doDel(Ids) {

            layer.confirm('确定要删除吗?', {

                skin: 'layui-layer-admin',

                shade: .1

            }, function (i) {

                layer.close(i);

                layer.load(2);

                $.post('{:url("del")}', {

                    ids: Ids

                }, function (res) {

                    layer.closeAll('loading');

                    if (res.code) {

                        layer.msg(res.msg, {icon: 1});

                        insTb.reload();

                    } else {

                        layer.msg(res.msg, {icon: 2});

}

                }, 'json');

});

}

        // 显示表单弹窗

        function showDetailModel(mData) {

            var shtml='';

            laytpl($('#modelView').html()).render(mData,function (html) {

                shtml=html

            });

            parent.layui.admin.open({

                type: 1,

                title: (mData ? '查看' : '添加') + '日志',

                shadeClose:true,

                content: shtml,

                area: ['700px'],

                success: function (layero, dIndex) {

                    $(layero).children('.layui-layer-content').css('overflow', 'visible');

}

});

}

});

</script>

atable.js 代码


/**

@ Name:表格冗余列可展开显示

@ Author:hbm

@ License:MIT

*/

layui.define(['form', 'table'], function (exports) {

    var $ = layui.$

        , table = layui.table

        ,hint = layui.hint()

        , form = layui.form

        , VERSION = 3.0, MOD_NAME = 'atable', ELEM = '.layui-atable', ON = 'on', OFF = 'off';

    //日期格式化

    Date.prototype.format = function (format) {

        var args = {

            "M+": this.getMonth() + 1,

            "d+": this.getDate(),

            "h+": this.getHours(),

            "m+": this.getMinutes(),

            "s+": this.getSeconds(),

            "q+": Math.floor((this.getMonth() + 3) / 3), //quarter

            "S": this.getMilliseconds()

};

        if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));

        for (var i in args) {

            var n = args[i];

            if (new RegExp("(" + i + ")").test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? n : ("00" + n).substr(("" + n).length));

}

        return format;

};

    //获取字面量数组的第一个id项

    var  paraGetOneId = function (para) {

                if(para.length==0){

                    return null;

                }else{

                    var temp=para[0];

                    return temp.id;

}

}

        ,paraGetId = function (para) {

            var ids=[];

            if(para.length==0){

                return null;

}

            for(var i=0;i<para.length;i++){

                ids.push(para[i].id)

}

            return ids;

}

        //外部接口

        , atable = {

            config: table.config,

            index: layui.table.index,

            cache: layui.table.cache

            //设置全局项

            , set: layui.table.set

            //事件监听

            , on: layui.table.on

            , reload: layui.table.reload

            , init: layui.table.init

            , checkStatus: layui.table.checkStatus

        }

        //操作当前实例

        , thisIns = function () {

            var that = this

                , options = that.config

                , id = options.id || options.index;

            if(id){

                thisIns.that[id] = that; //记录当前实例对象

                thisIns.config[id] = options; //记录当前实例配置项

            }

            return {

                config: options

                ,reload: function(options){

                    console.log(options);

                    that.reload.call(that, options);

}

                ,setColsWidth: function(){

                    that.setColsWidth.call(that);

}

                ,resize: function(){ //重置表格尺寸/结构

                    that.resize.call(that);

}

                ,getData: function () {

                    //获取数据

                    return table.checkStatus(that.config.id).data;

}

                ,getStatus: function () {

                    var checkStatus = table.checkStatus(that.config.id);

                    return checkStatus;

}

                ,getOne: function () {

                    var table_data = this.getData();

                    if (table_data == null) {

                        layer.msg("无法获取选中数据", {icon: 2});

                        return null;

}

                    if (table_data.length != 1) {

                        if (table_data.length == 0) {

                            layer.msg("至少要选中一条数据", {icon: 2});

                        } else {

                            layer.msg("只能选择一条数据", {icon: 2});

}

                        return null;

}

                    var one_id = paraGetOneId(table_data);

                    if (one_id == null) {

                        layer.msg("无法获取选中行id", {icon: 2});

                        return null;

}

                    return one_id;

}

                ,getMany: function (type = false) {

                    var table_data = this.getData();

                    if (table_data == null) {

                        layer.msg("无法获取选中数据", {icon: 2});

                        return null;

}

                    if (table_data.length < 1) {

                        layer.msg("至少要选中一条数据", {icon: 2});

                        return null;

}

                    var many_id = paraGetId(table_data);

                    if (many_id == null) {

                        layer.msg("无法获取选中行id", {icon: 2});

                        return null;

}

                    if (type) return many_id;

                    return many_id.join(',');

}

                ,search: function (search_param=[],page=1) {

                    var search_param = {

                        where: search_param,

                        page: {

                            curr: page

                        }

};

                    this.reload.call(that, search_param);

}

}

}

        //获取当前实例配置项

        ,getThisTableConfig = function(id){

            var config = thisIns.config[id];

            if(!config) hint.error('The ID option was not found in the table instance');

            return config || null;

}

        //构造器

        , Class = function (options) {

            var that = this;

            that.index = ++atable.index;

            that.config = $.extend({}, that.config, atable.config, options);

            that.render();

            return this;

};

    //默认配置

    Class.prototype.config = {

        checkbox:false  //单击勾选

        ,request: {

            //页码的参数名称,默认:page

                  pageName: 'page'

                //每页数据量的参数名,默认:limit

                , limitName: 'limit'

        }

        //对分页返回数据进行转换

        , parseData: function (res) {

            return {

                //解析接口状态

                "code": res.code,

                //解析提示文本

                "msg": res.msg,

                //解析数据长度

                "count": res.total,

                //解析数据列表

                "data": res.data

            };

}

        //接口http请求类型

        , method: 'get'

        , limit: 5

        , limits:[15,30,50,100]

};

    //渲染视图

    Class.prototype.render = function () {

        var that = this

            , options = that.config

            , instable = null;

        //  2、表格Render

        instable = table.render(options);

        //  当前表格 lay-filter ID

        var elem = $(options.elem).attr("lay-filter");

        //  5、监听表格排序

        table.on('sort(' + elem + ')', function (obj) {

            if (options.listen && options.listen.sort) {

                options.listen.sort(obj)

}

});

        //  监听单元格  单击事件

        table.on('row('+ elem +')', function(obj){

            var checkCell=obj.tr.find(".layui-form-checkbox");

            if(options.checkbox == true){

                if(obj.tr.hasClass('layui-table-click')){

                    obj.tr.removeClass('layui-table-click');

                    checkCell.removeClass('layui-form-checked');

                    table.cache[elem][obj.tr[0].rowIndex]['LAY_CHECKED'] = false;

                }else {

                    obj.tr.addClass('layui-table-click');

                    checkCell.addClass('layui-form-checked');

                    table.cache[elem][obj.tr[0].rowIndex]['LAY_CHECKED'] = true;

}

}

            if (options.listen && options.listen.click) {

                options.listen.click(obj)

}

});

        //  监听单元格  双击事件

        table.on('rowDouble('+ elem +')', function(obj){

            if (options.listen && options.listen.double) {

                options.listen.double(obj)

}

});

        //  监听单元格  编辑事件

        table.on('edit(' + elem + ')', function (obj) {

            if (options.listen && options.listen.edit) {

                options.listen.edit(obj)

}

});

        // 监听复选框事件

        table.on('checkbox(' + elem + ')', function(obj){

            if (options.listen && options.listen.checkbox) {

                options.listen.checkbox(obj)

}

});

        //  监听行工具栏 事件

        table.on('tool('+ elem +')', function (obj) {

            if (options.listen && options.listen.tool) {

                var event = obj.event ? obj.event : null;

                options.listen.tool(obj,event);

}

});

        // 监听表格头部工具栏事件

        table.on('toolbar('+elem+')', function(obj){

            switch(obj.event){

                case 'refresh':

                    instable.reload({page:{curr: 1}});

                    break;

}

            if (options.listen && options.listen.toolbar) {

                var event = obj.event ? obj.event : null;

                options.listen.toolbar(obj,event);

}

});

};

    //表格重载

    Class.prototype.reload = function(options){

        var that = this;

        options = options || {};

        delete that.haveInit;

        if(options.data && options.data.constructor === Array) delete that.config.data;

        that.config = $.extend(true, {}, that.config, options);

        that.render();

};

    //记录所有实例

    thisIns.that = {}; //记录所有实例对象

    thisIns.config = {}; //记录所有实例配置项

//核心入口

    atable.render = function (options) {

        var ins = new Class(options);

        return thisIns.call(ins);

};

    //在表头,以指定格式进行时间转换

    atable.date_format=function (date, format) {

        if(format==null){

            format="yyyy-MM-dd hh:mm:ss";

}

        if (date != null) {

            return new Date(date).format(format)

}

        return "";

};

    //设置状态

    atable.status = function(obj,status='status'){

        var strs = [

            '<span class="text-danger">停用</span>',

            '正常'

        ];

        return strs[obj.status];

};

    //表格重载

    atable.reload = function(id, options){

        var config = getThisTableConfig(id); //获取当前实例配置项

        if(!config) return;

        var that = thisIns.that[id];

        that.reload(options);

        return thisIns.call(that);

};

    exports('atable', atable);

});

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,546评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,224评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,911评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,737评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,753评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,598评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,338评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,249评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,696评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,888评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,013评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,731评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,348评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,929评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,048评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,203评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,960评论 2 355