Layui三方外掛OPTable的回撥

YangeraYR發表於2020-11-14

直接在layUI官方下載的opTable外掛,但是放在專案中一些回撥方法無法使用

解決方法

去碼雲上重新下載最新版本,layUI上不是最新的而且程式碼不完整,他的opTable.js中機會沒有文件中所寫的回撥方法

碼雲地址:https://gitee.com/Hbangmao/layui-op-table/blob/master/opTable/opTable.js

或者拷貝以下程式碼,注意其中最後引用的css的地址改為自己的

/**
 @ Name:layui 表格冗餘列可展開顯示
 @ Author:hbm
 @ License:MIT
 @ version 1.4
 */

layui.define(['form', 'table'], function (exports) {
    var $ = layui.$
        , table = layui.table
        , VERSION = 1.4, MOD_NAME = 'opTable'
        // 展開 , 關閉
        , ON = 'on', OFF = 'off', KEY_STATUS = "status"
        // openType 0、預設效果同時只展開一項  1、點選展開多項 2、 展開全部  3、關閉全部
        , OPEN_DEF = 0, OPEN_NO_CLOSE = 1, OPEN_ALL = 2, CLOSE_ALL = 3
        // 表頭展開所有圖示配置key,全部item 圖示配置key
        , ICON_DEF_ALL_KEY = "-1", ICON_DEF_ALL_ITEM_KEY = "0"
        // 外部介面
        , opTable = {
            index: layui.opTable ? (layui.opTable.index + 10000) : 0
            // 設定全域性項
            , set: function (options) {
                var that = this;
                that.config = $.extend({}, that.config, options);
                return that;
            }
        }
        // 展開列需要需要顯示的資料 資料格式為 每個頁面唯一的(LAY_IINDEX)下標繫結資料  對應的資料
        , openItemData = {}
        // 表格配置項,通過表格唯一ID繫結配置詳情 。
        , openTitleHelpOption = {}
        // 解決字表修改觸發父級表格修改的問題
        , isEditListener = true
        , getOpenClickClass = function (elem, isAddClickClass) {
            return elem.replace("#", '').replace(".", '') + (isAddClickClass ? 'opTable-i-table-open' : '')
        }
        , getOpenAllClickClass = function (elem) {
            return getOpenClickClass(elem, true) + "-all"
        }
        // 獲取展開全部圖示
        , getOpenAllIcon = function (isOpenTable, elem, icon) {
            return isOpenTable ? '' : '<i class="opTable-i-table-open ' + getOpenAllClickClass(elem) + ' " ' + KEY_STATUS + '="off"  title="(展開|關閉)全部" ' + icon + '></i>'
        }
        // 操作當前例項
        , thisIns = function () {
            var that = this
                , options = that.config
                , id = options.id || options.index;
            return {
                /**
                 * 過載  penTable
                 * @param options layui table 引數 和opTable引數
                 * @returns {thisIns}
                 */
                reload: function (options) {
                    options = options || {};
                    that.config = $.extend(that.config, options);
                    // 如果本次reload有頁碼則不使用上次記錄的頁碼
                    if (!options.page && that.config.table.config.page) {
                        that.config.page.limit = that.config.table.config.page.limit;
                        that.config.page.curr = that.config.table.config.page.curr;
                    }

                    that.render();
                    return this;
                }
                , config: options

                // 展開全部
                , openAll: function (result) {
                    if (this.isOpenAll()) {
                        result && result();
                        return this;
                    }
                    var def = that.config.openType;
                    that.config.openType = OPEN_ALL;
                    $("." + getOpenClickClass(that.config.elem, true)).parent().click();
                    that.config.openType = def;

                    $("." + getOpenAllClickClass(that.config.elem))
                        .addClass("opTable-open-dow")
                        .removeClass("opTable-open-up")
                        .attr(KEY_STATUS, ON);

                    that.config.onOpenAll && that.config.onOpenAll();
                    result && result();
                    return this;
                }
                // 關閉全部
                , closeAll: function () {
                    if (!this.isOpenAll()) {
                        return this;
                    }

                    var def = that.config.openType;
                    that.config.openType = CLOSE_ALL;
                    $("." + getOpenClickClass(that.config.elem, true)).parent().click();
                    that.config.openType = def;

                    $("." + getOpenAllClickClass(that.config.elem))
                        .addClass("opTable-open-up")
                        .removeClass("opTable-open-dow")
                        .attr(KEY_STATUS, OFF);

                    that.config.onCloseAll && that.config.onCloseAll();
                    return this;
                }

                // 通過下標展開一項
                , openIndex: function (index) {
                    var dom = $("." + getOpenClickClass(that.config.elem, true)).eq(index);
                    if (dom.length <= 0) {
                        return false;
                    }
                    var status = dom.attr(KEY_STATUS);
                    if (status === ON) {
                        return true;
                    }
                    dom.click();
                    return true;
                }
                // 通過下標展開一項
                , closeIndex: function (index) {
                    var dom = $("." + getOpenClickClass(that.config.elem, true)).eq(index);
                    if (dom.length <= 0) {
                        return false;
                    }
                    var status = dom.attr(KEY_STATUS);
                    if (status === OFF) {
                        return true;
                    }
                    dom.click();
                    return true;
                }
                // 當前展開狀態取反
                , toggleOpenIndex: function (index) {
                    var dom = $("." + getOpenClickClass(that.config.elem, true)).eq(index);
                    if (dom.length <= 0) {
                        return false;
                    }
                    dom.parent().click();
                    return true;
                }
                // 當前是否全部展開
                , isOpenAll: function () {
                    var localTag = $("." + getOpenClickClass(that.config.elem, true));
                    var isOpenAll = [];
                    localTag.each(function (i) {
                        if (localTag.eq(i).hasClass("opTable-open-dow")) {
                            isOpenAll.push(true)
                        }
                    });
                    // 所有項===已展開項則為全部展開
                    return localTag.length === isOpenAll.length;
                }
                // 展開所有樹形表格子表
                , openTreeChildTable: function () {

                }
                // 關閉所有樹形表格子表
                , closeTreeChildTable: function () {

                }
            }
        }
        //構造器
        , Class = function (options) {
            var that = this;
            that.index = ++opTable.index;
            that.config = $.extend({}, that.config, opTable.config, options);
            that.render();
            return this;
        };

    //預設配置
    Class.prototype.config = {
        // 是否顯示展開 預設顯示
        openVisible: true
        // 是否支援展開全部
        , isOpenAllClick: true
        , openType: OPEN_DEF
        // 展開的item (垂直v|水平h) 排序
        , opOrientation: 'v'
        // 在那一列顯示展開操作 v1.2
        , openColumnIndex: 0
        // 是否單獨佔一列 v1.2
        , isAloneColumn: true
        // 展開圖示 {"-1":'展開全部',0:'所有item下標',1:'' ,... 配置指定下標}
        , openIcon: {}
        // layui table引用
        , table: null
        // 展開動畫執行時長
        , slideDownTime: 200
        // 關閉動畫執行時長
        , slideUpTime: 100
    };

    //渲染檢視
    Class.prototype.render = function () {
        var that = this
            , options = that.config
            , colArr = options.cols[0]
            , openCols = options.openCols || []
            , openNetwork = options.openNetwork || null
            , openTable = options.openTable || null;

        options.layuiDone = options.done || options.layuiDone;

        var singleElem = options.elem.replace("#", '').replace(".", '')

        colArr.forEach(function (it, i) {
            // 當前列屬於圖示列
            if (it.isOpenCol) {
                // 獨佔一行 移除行
                if (options.isAloneColumn) {
                    colArr.splice(i, 1);
                } else {
                    // 移除合併圖示
                    it.title = it.opDefTitle || it.title;
                }
            }
            if (it.opHelp) {
                it.title = it.title.indexOf('opTable-span-help') === -1
                    ? it.title + '<span class="opTable-span-help" single="' + singleElem + it.field + '"></span>'
                    : it.title;
                openTitleHelpOption[singleElem + it.field] = it.opHelp;
            }
        });

        // 下標越界問題
        options.openColumnIndex = options.openColumnIndex > colArr.length ? colArr.length : options.openColumnIndex;
        delete options["done"];


        // 圖示
        var allIcon = function () {
            // 全部圖示
            var icon = options.openIcon[ICON_DEF_ALL_KEY];
            if (icon) {
                return "style='background: url(" + icon + ") 0 0 no-repeat'";
            }
            return "";
        }
            , allItemIcon = function () {
            // 全部item圖示
            var icon = options.openIcon[ICON_DEF_ALL_ITEM_KEY];
            if (icon) {
                return "style='background: url(" + icon + ") 0 0 no-repeat'";
            }
            return "";
        }
            , indexByIcon = function (index) {
            // 指定下標圖示
            var iconPath = options.openIcon[index + ""];
            if (iconPath) {
                return "style='background: url(" + iconPath + ") 0 0 no-repeat'"
            }
            return allItemIcon;
        };


        if (options.openVisible) {
            //1、 單獨佔一列
            if (options.isAloneColumn) {
                //  1、在指定列 插入可展開操作
                colArr.splice(options.openColumnIndex, 0, {
                    width: 50,
                    isOpenCol: true,
                    title: getOpenAllIcon(!options.isOpenAllClick, options.elem, allIcon()),
                    templet: function (item) {
                        // 解決頁面多個表格問題
                        var cla = getOpenClickClass(options.elem, false);
                        openItemData[cla] = openItemData[cla] || {};
                        openItemData[cla][item.LAY_INDEX] = item;
                        return "<i class='opTable-i-table-open " + cla + "opTable-i-table-open' " + KEY_STATUS + "='off'  data='"
                            //  把當前列的資料繫結到控制元件
                            + item.LAY_INDEX
                            + " ' elem='"
                            + cla
                            + "' title='展開' " + indexByIcon(item.LAY_INDEX) + "></i>";
                    }
                });
            } else {
                //2、與資料佔一列
                var openColumn = colArr[options.openColumnIndex];
                delete openColumn["edit"];
                openColumn.opDefTitle = openColumn.title;
                openColumn.isOpenCol = true;
                // 存在排序 都不支援展開全部
                openColumn.title = getOpenAllIcon(openColumn["sort"], options.elem, allIcon()) + ("<span class='opTable-span-seize'></span>") + openColumn.title;
                openColumn.templet = function (item) {
                    var cla = getOpenClickClass(options.elem, false);
                    openItemData[cla] = openItemData[cla] || {};
                    openItemData[cla][item.LAY_INDEX] = item;
                    return ("<i class='opTable-i-table-open " + cla + "opTable-i-table-open' " + KEY_STATUS + "='off'  data='"
                        //  把當前列的資料繫結到控制元件
                        + item.LAY_INDEX
                        + " ' elem='"
                        + cla
                        + "' title='展開' "
                        + indexByIcon(item.LAY_INDEX) + "></i>")
                        + ("<span class='opTable-span-seize'></span>")
                        + (openColumn.onDraw ? openColumn.onDraw(item) : item[openColumn.field]);
                };
            }
        }


        //  2、表格Render
        options.table = table.render(
            $.extend({
                done: function (res, curr, count) {
                    initExpandedListener();
                    options.layuiDone && options.layuiDone(res, curr, count)
                }
            }, options));


        // 3、展開事件
        function initExpandedListener() {
            if (!options.openVisible) {
                return;
            }

            $("." + getOpenClickClass(options.elem, true))
                .parent()
                .unbind("click")
                .click(function (e) {
                    layui.stope(e);
                    var that = $(this).children()
                        , _this = this
                        , itemIndex = parseInt(that.attr("data"))
                        , bindOpenData = openItemData[that.attr("elem")][itemIndex]
                        , status = that.attr(KEY_STATUS) === 'on'
                        // 操作倒三角
                        , dowDom = that.parent().parent().parent().parent().find(".opTable-open-dow")
                        // 展開的tr
                        , addTD = that.parent().parent().parent().parent().find(".opTable-open-td"),
                        // 行點選Class
                        itemClickClass = options.elem.replace("#", '').replace(".", '') + '-opTable-open-item-div';

                    function initOnClose() {
                        options.onClose && options.onClose(bindOpenData, itemIndex);
                    }

                    // 關閉全部
                    if (options.openType === CLOSE_ALL) {
                        dowDom
                            .addClass("opTable-open-up")
                            .removeClass("opTable-open-dow")
                            .attr(KEY_STATUS, OFF);
                        addTD.slideUp(options.slideUpTime, function () {
                            addTD.remove();
                        });
                        //關閉回撥
                        initOnClose();
                        return;
                    }

                    // 展開全部
                    if (options.openType === OPEN_ALL) {
                        dowDom
                            .addClass("opTable-open-dow")
                            .removeClass("opTable-open-up")
                            .attr(KEY_STATUS, ON);
                        if (status) {
                            _this.addTR.remove();
                        }
                    } else if (options.openType === OPEN_DEF) {
                        // 關閉型別
                        var sta = dowDom.attr(KEY_STATUS),
                            isThis = (that.attr("data") === dowDom.attr("data"));
                        //1、關閉展開的
                        dowDom
                            .addClass("opTable-open-up")
                            .removeClass("opTable-open-dow")
                            .attr(KEY_STATUS, OFF);

                        //2、如果當前 = 展開 && 不等於當前的 關閉
                        if (sta === ON && isThis) {
                            addTD.slideUp(options.slideUpTime, function () {
                                addTD.remove();
                                initOnClose();
                            });
                            return;
                        } else {
                            that.attr(KEY_STATUS, OFF);
                            addTD.remove();
                        }
                    } else if (options.openType === OPEN_NO_CLOSE) {
                        //  1、如果當前為開啟,再次點選則關閉
                        if (status) {
                            that.removeClass("opTable-open-dow");
                            that.attr(KEY_STATUS, OFF);
                            this.addTR.find("div").eq(0).slideUp(options.slideUpTime, function () {
                                _this.addTR.remove();
                                //關閉回撥
                                initOnClose();
                            });
                            return;
                        }

                    }

                    // 把新增的 tr 繫結到當前 移除時使用 獨佔一列時 將表格列分配+1
                    this.addTR = $([
                        "<tr><td class='opTable-open-td'  colspan='" + (colArr.length + (options.isAloneColumn ? 1 : 0)) + "'>"
                        , "<div style='margin-left: 50px;display: none'></div>"
                        , "</td></tr>"].join("")
                    );

                    // 所有內容的主容器
                    var divContent =
                        _this.addTR
                            .children()
                            .children();

                    that.parent().parent().parent().after(this.addTR);

                    var html = [];

                    // 1、從網路獲取
                    if (openNetwork) {
                        loadNetwork();
                    }
                    // 2、展開顯示錶格
                    else if (openTable) {
                        if (typeof openTable !== "function") {
                            throw  "OPTable: openTable attribute is function ";
                        }
                        var tableOptions = openTable(bindOpenData);
                        tableOptions.layuiDone = tableOptions.done;
                        tableOptions.done = function (res, curr, count) {
                            // 子錶行聚焦向上傳遞問題
                            $(".opTable-open-td tr").hover(function (e) {
                                layui.stope(e)
                            });

                            /* $("tr").click(function (e) {
                               setTimeout(function () {
                                 $(".layui-table-click").removeClass('layui-table-click');
                               }, 40);
                               // layui.stope(e);
                             });*/

                            // 子表排序
                            tableOptions.layuiDone && tableOptions.layuiDone(res, curr, count);
                        };

                        var id = tableOptions.elem.replace("#", '').replace(".", '');

                        divContent
                            .empty()
                            .append("<table id='" + id + "' lay-filter='" + id + "'></table>")
                            .css({
                                "padding": "0 10px 0 50px", "margin-left": "0", "width":
                                    _this.addTR.width()
                            })
                            .fadeIn(400);

                        // 設定展開表格顏色為淺色背景
                        addTD.css("cssText", "background-color:#FCFCFC!important");
                        layui.opTable.render(tableOptions);
                    }
                    // 3、從左到右依次排列 Item 預設風格
                    else {
                        openCols.forEach(function (val, index) {
                            appendItem(val, bindOpenData);

                        });
                        divContent.append(html.join(''));
                        this.addTR.find("div").slideDown(options.slideDownTime);
                        bindBlur(bindOpenData);
                    }

                    function loadNetwork() {
                        divContent.empty()
                            .append('<div class="opTable-network-message" ><i class="layui-icon layui-icon-loading layui-icon layui-anim layui-anim-rotate layui-anim-loop" data-anim="layui-anim-rotate layui-anim-loop"></i></div>');
                        _this.addTR.find("div").slideDown(options.slideDownTime);


                        openNetwork.onNetwork(bindOpenData
                            //載入成功
                            , function (obj) {
                                //  2、從左到右依次排列 Item
                                openNetwork.openCols.forEach(function (val, index) {
                                    appendItem(val, obj);
                                });
                                // 填充展開資料
                                divContent.empty().append(html.join(''));
                                bindBlur(obj);
                            }
                            , function (msg) {
                                divContent.empty()
                                    .append("<div class='opTable-reload opTable-network-message' style='text-align: center;margin-top: 20px'>" + (msg || "沒有資料") + "</div>")

                                $(".opTable-reload")
                                    .unbind()
                                    .click(function (e) {
                                        loadNetwork();
                                    });
                            })
                    }


                    /**
                     * 新增預設排版風格 item
                     * @param colsItem  cols配置資訊
                     * @param openData  展開資料
                     */
                    function appendItem(colsItem, openData) {
                        // 顯示幫助圖示
                        if (colsItem.opHelp) {
                            colsItem.title = colsItem.title.indexOf('opTable-span-help') === -1
                                ? colsItem.title + '<span class="opTable-span-help" single="' + singleElem + colsItem.field + '"></span>'
                                : colsItem.title;
                            openTitleHelpOption[singleElem + colsItem.field] = colsItem.opHelp;
                        }

                        //  1、自定義模板
                        if (colsItem.templet) {
                            html.push("<div id='" + colsItem.field + "' class='opTable-open-item-div " + itemClickClass + "' index='" + itemIndex + "' opOrientation='" + options.opOrientation + "'>")
                            html.push(colsItem.templet(openData));
                            html.push("</div>")
                            //  2、可下拉選擇型別
                        } else if (colsItem.type && colsItem.type === 'select') {
                            var child = ["<div id='" + colsItem.field + "' class='opTable-open-item-div " + itemClickClass + "' index='" + itemIndex + "' opOrientation='" + options.opOrientation + "' >"];
                            child.push("<span style='color: #99a9bf'>" + colsItem["title"] + ":</span>");
                            child.push("<div class='layui-input-inline'><select  lay-filter='" + colsItem.field + "'>");
                            colsItem.items(openData).forEach(function (it) {
                                child.push("<option value='" + it.id + "' ");
                                child.push(it.isSelect ? " selected='selected' " : "");
                                child.push(" >" + it.value + "</option>");
                            });
                            child.push("</select></div>");
                            child.push("</div>");
                            html.push(child.join(""));
                            setTimeout(function () {
                                layui.form.render();
                                //  監聽 select 修改
                                layui.form.on('select(' + colsItem.field + ')', function (data) {
                                    if (options.onEdit && colsItem.isEdit && colsItem.isEdit(data, openData)) {
                                        var json = {};
                                        json.value = data.value;
                                        json.field = colsItem.field;
                                        openData[colsItem.field] = data.value;
                                        json.data = JSON.parse(JSON.stringify(openData));
                                        options.onEdit(json);
                                    }
                                });
                            }, 20);
                        } else {
                            var text = colsItem.onDraw ? colsItem.onDraw(openData) : openData[colsItem["field"]];
                            // 處理null字串問題
                            text = text || "";
                            // 3、預設型別
                            html.push("<div id='" + colsItem.field + "' class='opTable-open-item-div " + itemClickClass + "' index='" + itemIndex + "' opOrientation='" + options.opOrientation + "'>");
                            html.push("<span class='opTable-item-title'>" + colsItem["title"] + ":</span>");
                            html.push((colsItem.edit ?
                                    ("<input  class='opTable-exp-value opTable-exp-value-edit' autocomplete='off' name='" + colsItem["field"] + "' value='" + text + "'/>")
                                    : ("<span class='opTable-exp-value' >" + text + "</span>")
                            ));
                            html.push("</div>");
                        }

                    }

                    /**
                     * 繫結監聽 修改失焦點監聽
                     * @param bindOpenData
                     */
                    function bindBlur(bindOpenData) {
                        $(".opTable-exp-value-edit")
                            .unbind("blur")
                            .blur(function () {
                                var that = $(this), name = that.attr("name"), val = that.val();
                                // 設定了回撥 &&發生了修改
                                if (options.onEdit && bindOpenData[name] + "" !== val) {
                                    var json = {};
                                    json.value = that.val();
                                    json.field = that.attr("name");
                                    bindOpenData[name] = val;
                                    json.data = bindOpenData;
                                    options.onEdit(json);
                                }
                            })
                            .keypress(function (even) {
                                even.which === 13 && $(this).blur()
                            })
                    }


                    if (options.onItemClick) {
                        $("." + itemClickClass)
                            .unbind("click")
                            .click(function (e) {
                                var field = $(this).attr("id");
                                // 根據下標獲取行資料
                                var lineData = openItemData[getOpenClickClass(options.elem, false)][$(this).attr("index")];
                                options.onItemClick({
                                    lineData: lineData,
                                    field: field,
                                    value: lineData[field],
                                    div: $(this),
                                    e: e
                                });
                            });
                    }

                    that.addClass("opTable-open-dow");
                    that.attr(KEY_STATUS, ON);

                    // 建立成功回撥
                    options.onInitSuccess && options.onInitSuccess(bindOpenData, itemIndex, this.addTR);
                    setTimeout(function () {
                        // 展開回撥
                        options.onOpen && options.onOpen(bindOpenData, itemIndex, that.addTR);
                        initHelpListener();
                    }, options.slideDownTime);

                });

            // (展開|關閉)全部
            $("." + getOpenAllClickClass(options.elem))
                .parent()
                .parent()
                .unbind("click")
                .click(function () {
                    if (!options.isOpenAllClick) {
                        return
                    }

                    var tag = $(this).find("i").eq(0), status = tag.attr(KEY_STATUS);
                    if (status === ON) {
                        tag.addClass("opTable-open-up")
                            .removeClass("opTable-open-dow")
                            .attr(KEY_STATUS, OFF);
                        options.thisIns.closeAll();
                    } else {
                        tag
                            .addClass("opTable-open-dow")
                            .removeClass("opTable-open-up")
                            .attr(KEY_STATUS, ON);
                        options.thisIns.openAll();
                    }

                });

            initHelpListener();
        }


        // 彈出幫助提示
        function initHelpListener() {
            $(".opTable-span-help").unbind("click").click(function () {
                var that = $(this);
                var opt = openTitleHelpOption[that.attr("single")];
                var index = layer.tips(opt.text + "<span class='op-span-help-close'>關閉</span>", that.parent(), $.extend({
                    tips: 3, time: 40000, success: function () {
                        $(".op-span-help-close").click(function () {
                            layer.close(index);
                        })
                    }
                }, opt.tipOpt))
            });

        }

        //  4、監聽排序事件
        var elem = $(options.elem).attr("lay-filter");

        //  5、監聽表格排序
        table.on('sort(' + elem + ')', function (obj) {
            options.onSort && options.onSort(obj);
            // 重新繫結事件
            initExpandedListener();
        });

        //  6、單元格編輯
        layui.table.on('edit(' + elem + ')', function (obj) {
            if (!isEditListener) {
                return;
            }
            isEditListener = false;
            options.onEdit && options.onEdit(obj);
            setTimeout(function () {
                isEditListener = true;
            }, 100);
        });

    };

    //核心入口
    opTable.render = function (options) {
        var ins = new Class(options);
        var ex = thisIns.call(ins);
        ins.config.thisIns = ex;
        return ex;
    };

    //載入元件所需樣式
    layui.link(layui.cache.base + '/opTable/opTable.css?v=1' + VERSION, function () {
    }, 'opTable');

    opTable.openTableVersion = VERSION;
    exports('opTable', opTable);
});

 

相關文章