layui treeTable

layui treeTablelayuitable结构不能很直观的展示层级信息,所以参考”https://fly.layui.com/extend/treeTable/”组件(layui版本为v2.5.6),修改为树形展示,修改了treeTable.js,保留了一些原table定义;修改如下:支持reload,post方式拉取数据,参考table配置(操作列支持toolbar,cols结构,checkStatus),check_mode(0上下级联勾选默认,1单选,2多选[不级联]),open_all(默认展开全部),level_

layui table结构不能很直观的展示层级信息,所以参考”https://fly.layui.com/extend/treeTable/“组件(layui版本为v2.5.6),修改为树形展示,修改了treeTable.js,保留了一些原table定义;

修改如下:支持reload,post方式拉取数据,参考table配置(操作列支持toolbar,cols结构,checkStatus),check_mode(0上下级联勾选默认,1单选,2多选[不级联]),open_all(默认展开全部),level_key(层级字段),level_start(实际层级最小值,默认为0,第一级展示的时候保证没有左边距)

id,elem必须一致,不过elem加了”#”

缺点:一次拉取所有数据,数据量大的时候不能动态刷新子节点(待改进)

departList.cshtml

@model Web.Admin.Models.DepartListViewModel
@{ 
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>部门管理</title>
    <meta name="referrer" content="no-referrer" />
    <link href="/components/layui/css/layui.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div class="layui-row" id="pic-search">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body">
                    <form class="layui-form" lay-filter="searchForm">
                        <div class="layui-input-inline layui-col-md6">
                            @Html.TextBoxFor(x => x.keyword, new { placeholder = "关键字", @class = "layui-input" })
                        </div>
                        <div class="layui-input-inline layui-col-md3">
                            <button type="button" id="btnSearch" class="layui-btn">查询</button>
                            @if (Model.edit)
                            {
                                <button type="button" id="btnAdd" class="layui-btn">新增</button>
                            }
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <div id="data-list" style="margin:10px 10px 0px;">
        <table class="layui-table layui-form" id="departTable" lay-filter="table"></table>
    </div>
    <div id="dlg-edit" style="display:none;padding:20px 30px 0 0;">
        <form class="layui-form" lay-filter="editForm">
            <div class="layui-form-item">
                <label class="layui-form-label">名称</label>
                <div class="layui-input-block">
                    <input type="text" name="dpname" lay-verify="required" autocomplete="off" placeholder="机构名称不能为空" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">院校</label>
                <div class="layui-input-block">
                    <select name="parentid"></select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">排序</label>
                <div class="layui-input-block">
                    <input type="number" value="0" min="0" name="displayorder" autocomplete="off" lay-verify="required|number" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                    <textarea name="remark" placeholder="请输入内容" class="layui-textarea"></textarea>
                </div>
            </div>
        </form>
    </div>
    <script type="text/html" id="toobar">
        <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</a>
        @if (Model.edit)
        {
        <a class="layui-btn layui-btn-xs" lay-event="update">修改</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
        }
    </script>
    <script src="/scripts/jquery.js"></script>
    <script src="/components/layui/layui.js"></script>
    <script>
        layui.config({
            base: "../../../components/layui/"//基于当前页面,查找treeTable.js文件所在目录
        });

        //获取选择的项
        function getChecked() {
            return layui.treeTable.checkStatus("departTable");
        }

        function getQueryParas() {
            return layui.form.getValue("searchForm");
        }

        function search() {
            var index = layui.layer.load(1);//开启进度条
            layui.treeTable.reload('departTable', {
                where: getQueryParas(),
                done: function (res) {
                    layer.close(index);
                }
            });
        }

        function openDetail(data) {
            showEditDlg({
                title: "查看",
                btn: ["关闭"],
                success: function () {
                    layui.form.val("editForm", data);
                },
                yes: function (index) {
                    layui.layer.close(index);
                }
            }, 2);
        }

        function showEditDlg(option, m) {
            var index = layui.layer.load(1);
            $.get("/admin/user/GetTopDepartList", function (data) {
                var dd = $("#dlg-edit select[name='parentid']").empty();
                if (m == 2) {
                    //查看
                    $("#dlg-edit").addClass("layui-disabled");
                }
                else {
                    $("#dlg-edit").removeClass("layui-disabled");
                    if (m == 0) {
                        //重置表单
                        layui.form.val("editForm", $("#dlg-edit").data("default"));
                        //新增
                        dd.prop("disabled", false);
                    }
                    else if (m == 1) {
                        //编辑
                        dd.prop("disabled", true);
                    }
                }
                dd.append("<option value=\"0\">顶级单位</option>");
                if (data && data.length) {
                    $.each(data, function (i, o) {
                        dd.append($("<option>").attr("value", o.dpid).text(" " + o.dpname));
                    });
                    dd.val(data[0].dpid);
                }
                layui.form.render("select", "editForm");
                layui.layer.close(index);
                var opt = $.extend({
                    type: 1,
                    shadeClose: false,
                    btnAlign: 'c',
                    shade: 0.3,
                    maxmin: false,
                    area: ['600px', '400px'],
                    content: $("#dlg-edit")
                }, option);
                layui.layer.open(opt);
            });
        }
        @if(Model.edit)
        {
         <text>
         function addDepart() {
            showEditDlg({
                title: "新增机构",
                btn: ["确定", "取消"],
                yes: function (index) {
                    data = layui.form.getValue("editForm");
                    $.post("/admin/user/saveDepart", data, function (rsp) {
                        if (rsp.success) {
                            layui.layer.close(index);
                            layui.layer.msg("保存成功!", { time: 1500}, function () {
                                search();
                            });
                        }
                        else {
                            layui.layer.alert(rsp.message);
                        }
                  });
                }
            },0);
         }

        function updateDepart(data) {
            showEditDlg({
            title: "修改机构",
                btn: ["确定", "取消"],
                success: function () {
                    layui.form.val("editForm", data);
                },
                yes: function (index) {
                    data = $.extend(data, layui.form.getValue("editForm"));
                    $.post("/admin/user/saveDepart", data, function (rsp) {
                        if (rsp.success) {
                            layui.layer.close(index);
                            layui.layer.msg("保存成功!", { time: 1500 }, function () {
                                search();
                            });
                        }
                        else {
                            layui.layer.alert(rsp.message);
                        }
                    });
                }
            },1);
        }

        function delDepart(dp) {
            layui.layer.confirm("确定要删除" + dp.dpname + "吗?", function (idx) {
                $.get("/admin/user/DelDepart", { dpid: dp.dpid }, function (rsp) {
                    if (rsp.success) {
                        layui.layer.close(index);
                        layui.layer.msg("操作成功!", { time:1500}, function () {
                            search();
                        });
                    }
                    else {
                        layui.layer.alert(rsp.message);
                    }
                });
            });
        }</text>
        }

        layui.use(["treeTable", "form", "layer", "laytpl", "upload"], function () {
            var layer = layui.layer;
            var index = layer.load(1);//开启进度条
            layui.treeTable.render({
                elem: '#departTable',//table id
                url: '/admin/user/SearchDepartList',
                method: 'POST', //方式
                cellMinWidth: 120,
                even: true, //开启隔行背景
                id: 'departTable',
                top_value: "0",
                primary_key: "dpid",
                parent_key: 'parentid',
                level_key: 'layer',
                level_start: 1,
                height: 'full-200',
                icon_key: 'dpname',
                is_checkbox: true,
                check_mode:@Model.checkMode,
                checked: {
                    key: 'dpid',
                },
                open_all: true,
                done: function (res, curr, count) {
                    layer.close(index);//关闭
                },
                cols: [[
                    {
                        key: 'dpname',
                        title: '名称',
                        width: "200px"
                    },
                    {
                        key: 'addtime',
                        title: '创建时间',
                        align: 'center',
                        width: "150px"
                    },
                    {
                        key: 'remark',
                        title: '备注',
                        width: "200px"
                    },
                    {
                        title: '操作',
                        align: 'center',
                        toolbar: '#toobar',
                        width: "200px"
                    }]]
            });

            layui.treeTable.on('tool(table)', function (obj) {
                var data = obj.data, layEvent = obj.event;
                if (layEvent === 'detail') {
                    openDetail(data);
                }
                @if (Model.edit)
                {
                    <text>if (layEvent === 'update') {
                    updateDepart(data);
                }
                if (layEvent === 'del') {
                    delDepart(data);
                }</text>
                }
            });
            $("#dlg-edit").data("default", layui.form.getValue("editForm"));
            search();
        });

        $(function () {
            $("#btnSearch").click(search);
            @if (Model.edit)
            { 
            <text>$("#btnAdd").click(addDepart);</text>
            }
        });
    </script>
</body>
</html>

controller

namespace Web.Admin.Controllers
{
    /// <summary>
    /// 后台用户控制器类
    /// </summary>
    public partial class UserController : BaseAdminController
    {
        /// <summary>
        /// 部门管理
        /// </summary>
        /// <returns></returns>
        public ActionResult DepartList(string keyword,bool edit = true,int mode = 0)
        {
            DepartListViewModel model = new DepartListViewModel();
            model.keyword = keyword;
            model.edit = edit;
            model.checkMode = mode;
            return View(model);
        }

        /// <summary>
        /// 查询单位,属性结构显示
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public JsonResult SearchDepartList(string keyword)
        {
            return ToJson(Users.SearchDepartment(keyword), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取顶级单位信息
        /// </summary>
        /// <returns></returns>
        public JsonResult GetTopDepartList()
        {
            return ToJson(Users.SearchDepartment(null,0), JsonRequestBehavior.AllowGet);
        }

        public JsonResult SaveDepart(SmartPig_Depart depart)
        {
            depart.addtime = DateTime.Now;
            depart.adduid = WorkContext.Uid;
            int result = Users.SaveDepart(depart);
            if (result == -1)
            {
                return Json(JsonResponse.Fail("父级不存在,请重新选择!"));
            }
            else if (result == -2)
            {
                return Json(JsonResponse.Fail("机构名称已存在!"));
            }
            else
            {
                return Json(JsonResponse.OK(null));
            }
        }

        public JsonResult DelDepart(int dpid)
        {
            int result = Users.DeleteDepart(dpid);
            if (result == -1)
            {
                return Json(JsonResponse.Fail("部门中有成员,不能执行删除操作!"), JsonRequestBehavior.AllowGet);
            }
            else if (result == -2)
            {
                return Json(JsonResponse.Fail("部门仓库不为空!"), JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(JsonResponse.OK(null), JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 输出Json格式
        /// </summary>
        /// <param name="data"></param>
        /// <param name="jsonRequestBehavior"></param>
        /// <returns></returns>
        protected JsonResult ToJson(object data,JsonRequestBehavior jsonRequestBehavior)
        {
            return new JsonNetResult(data, jsonRequestBehavior, CommonHelper._jsonSettings);
        }
    }
}

JsonNetResult.cs(日期转换)

public class JsonNetResult : JsonResult
{
	const string JsonType = "application/json";
	private JsonSerializerSettings _settings = null;

	public JsonNetResult()
	{
		this.ContentType = "application/json";
	}

	public JsonNetResult(object data, 
		JsonRequestBehavior jsonRequestBehavior = JsonRequestBehavior.AllowGet,
		JsonSerializerSettings settings = null,
		Encoding contentEncoding = null, 
		string contentType = JsonType)
	{
		this.Data = data;
		_settings = settings;
		this.JsonRequestBehavior = jsonRequestBehavior;
		if (contentEncoding != null)
		{
			this.ContentEncoding = contentEncoding;
		}
		this.ContentType = string.IsNullOrWhiteSpace(contentType) ? JsonType : contentType;
	}

	public override void ExecuteResult(ControllerContext context)
	{
		if (context == null)
			throw new ArgumentNullException("context");

		var response = context.HttpContext.Response;

		response.ContentType = string.IsNullOrEmpty(ContentType) ? ContentType : JsonType;

		if (ContentEncoding != null)
			response.ContentEncoding = ContentEncoding;

		if (Data == null)
			return;

		// If you need special handling, you can call another form of SerializeObject below
		var serializedObject = JsonConvert.SerializeObject(Data, Formatting.None, _settings);
		response.Write(serializedObject);
	}
}

CommonHelper.cs

public static JsonSerializerSettings _jsonSettings;

public static readonly System.Web.Script.Serialization.JavaScriptSerializer serializer = null;

public static readonly DateTime EpochTime = new DateTime(1970,1,1);

public static readonly char[] splitor = new char[] { (char)31};

public static readonly char[] spaceSplitor = new char[] { ' ' };

public const string Success = "SUCCESS";

static CommonHelper()
{
	IsoDateTimeConverter datetimeConverter = new IsoDateTimeConverter();
	datetimeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";

	_jsonSettings = new JsonSerializerSettings();
	_jsonSettings.MissingMemberHandling = MissingMemberHandling.Ignore;
	_jsonSettings.NullValueHandling = NullValueHandling.Ignore;
	_jsonSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
	_jsonSettings.Converters.Add(datetimeConverter);

	serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
}

treeTable.js

layui.define(['jquery'], function(exports) {
	var MOD_NAME = 'treeTable',
		o = layui.jquery,
		tree = function() {};
	tree.prototype.config = function() {
		return {
			top_value: 0,
			primary_key: 'id',
			parent_key: 'pid',
			level_key: 'level',
			level_start:0,
			hide_class: 'layui-hide',
			icon: {
				open: 'layui-icon layui-icon-triangle-d',
				close: 'layui-icon layui-icon-triangle-r',
				left: 16,
			},
			cols: [[]],
			checked: {},
			check_mode:0,
			is_click_icon: false,
			is_checkbox: false,
			is_head:true
		};
	}

	/**
	 * 设置列的样式
	 * @param {object} col
	 */
	function _setColStyle(col) {
		var style = "";
		col.width && (style += 'width:' + col.width + ';'), col.align && (style += 'text-align:' + col.align + ';'), style && (style = 'style="' + style + '"');
		col._style = style;
	}

	tree.prototype.template = function (e) {
		var t = this, tbody = '',
			is_table = o('table' + e.elem).length || !(e.is_click_icon = true),
			checkbox = e.is_checkbox ? '<div class="layui-unselect layui-form-checkbox cbx" lay-skin="primary"><i class="layui-icon layui-icon-ok"></i></div>' : '',
			checked = checkbox ? checkbox.replace('cbx', 'cbx layui-form-checked') : '',
			thead = checkbox && '<th style="width:28px;">' + (e.check_mode === 0 ? (o.inArray(e.top_value, e.checked.data) > -1 ? checked : checkbox) : "") + '</th>';
		//表头
		e.is_head && o.each(e.cols[0], function (index, obj) {
			obj._style === undefined && _setColStyle(obj);
			thead += '<th ' + obj._style + '>' + obj.title + '</th>';
		});
		o.each(this.data(e, e.data), function (idx, item) {
			var tr = '',
				is_checked = false,
				hide_class = (item[e.parent_key] == e.top_value) || (item[e.parent_key] == t.cache(e, item[e.parent_key])) ? '' : e.hide_class;
			// 设置每行数据层级
			// 设置是否为最后一级
			item.is_end = !e.childs[item[e.primary_key]];
			o.each(e.cols[0], function (index, obj) {
				obj._style === undefined && _setColStyle(obj);
				// 标记设置行checkbox选中
				if (e.is_checkbox && e.checked && o.inArray(item[e.checked.key], e.checked.data) > -1) {
					is_checked = true;
				}
				// 指定列加入开启、关闭小图标
				var icon = (obj.key == e.icon_key && !item.is_end) ? '<i class="' + (t.cache(e, item[e.primary_key]) ? e.icon.open : e.icon.close) + '"></i>' : '<span></span>';
				// 指定列小图标按照层级向后位移
				var left = (obj.key == e.icon_key ? (item[e.level_key] - e.level_start) * e.icon.left + 'px' : '');
				if (left) {
					icon = icon.replace('>', ' style="margin-left:' + left + ';">');
				}
				// 拼接行
				tr += '<td ' + obj._style + (left ? 'data-down' : '') + '>' + icon + (is_table ? '' : (is_checked ? checked : checkbox)) + (obj.template ? obj.template(item) : (obj.toolbar ? $(obj.toolbar).html() : (item[obj.key] || ""))) + '</td>';
			});
			var box = is_table ? o(is_checked ? checked : checkbox).wrap('<td style="width:28px;">').parent().prop('outerHTML') : '';
			tbody += '<tr class="' + hide_class + '" data-id="' + item[e.primary_key] + '" data-pid="' + item[e.parent_key] + '">' + box + tr + '</tr>';
		});
		// 处理表树和树的赋值模板
		var table = is_table ? '<thead><tr data-id="' + e.top_value + '">' + thead + '</tr></thead><tbody>' + tbody + '</tbody>' : tbody.replace(/<tr/g, '<ul').replace(/tr>/g, 'ul>').replace(/<td/g, '<li').replace(/td>/g, 'li>');
		// 确认点击图标或点击列触发展开关闭
		var click_btn = e.is_click_icon ? '[data-down] i:not(.layui-icon-ok)' : '[data-down]';
		// 模板渲染并处理点击展开收起等功能
		o(e.elem).html(table).off('click', click_btn).on('click', click_btn, function () {
			var tr = o(this).parents('[data-id]'),
				td = tr.find('[data-down]'),
				id = tr.data('id'),
				pid = tr.data('pid'),
				is_open = (td.find('i:not(.layui-icon-ok)').attr('class') == e.icon.close);
			if (is_open) {
				// 展开子级(子级出现、更改图标)
				td.find('i:not(.layui-icon-ok)').attr('class', e.icon.open);
				td.parents(e.elem).find('[data-pid=' + id + ']').removeClass(e.hide_class);
				t.cache(e, id, true);
			} else {
				// 关闭子级(更改图标、隐藏所有子孙级)
				td.find('i:not(.layui-icon-ok)').attr('class', e.icon.close);
				t.childs_hide(e, id);
			}
			// 设置监听展开关闭
			layui.event.call(this, MOD_NAME, 'tree(flex)', {
				elem: this,
				data: e.childs[pid][id],
				table: e.elem,
				is_open: is_open,
			})
		}).off('click', '.cbx').on('click', '.cbx', function () {
			var is_checked = o(this).toggleClass('layui-form-checked').hasClass('layui-form-checked'),
				tr = o(this).parents('[data-id]'),
				id = tr.data('id'),
				pid = tr.data('pid');
			if (e.check_mode == 0) {
				//默认
				t.childs_checkbox(e, id, is_checked);
				t.parents_checkbox(e, pid);
			}
			else if (e.check_mode == 1 && is_checked) {
				//单选
				o(e.elem).find(".cbx.layui-form-checked").removeClass('layui-form-checked');
				o(this).addClass("layui-form-checked");
			}
			// 设置监听checkbox选择
			layui.event.call(this, MOD_NAME, 'tree(box)', {
				elem: this,
				item: pid === undefined ? {} : e.childs[pid][id],
				table: e.elem,
				is_checked: is_checked,
			})
		}).off('click', '[lay-filter]').on('click', '[lay-filter]', function () {
			var tr = o(this).parents('[data-id]'),
				id = tr.data('id'),
				pid = tr.data('pid'),
				filter = o(this).attr("lay-filter");
			return layui.event.call(this, MOD_NAME, 'tree(' + filter + ')', {
				elem: this,
				data: e.childs[pid][id],
			})
		}).off('click', '[lay-event]').on('click', '[lay-event]', function () {
			var tr = o(this).parents('[data-id]'),
				filter = o(e.elem).attr("lay-filter"),
				id = tr.data('id'),
				pid = tr.data('pid'),
				event = o(this).attr("lay-event");
			return layui.event.call(this, MOD_NAME, 'tool(' + filter + ')', {
				elem: this,
				event: event,
				data: e.childs[pid][id],
			})
		});
		e.done && e.done(e);
	};

	// 同级全部选中父级选中/同级全部取消取消父级
	tree.prototype.parents_checkbox = function(e, pid) {
		var po = o(e.elem).find('[data-pid=' + pid + ']'),
			co = o(e.elem).find('[data-id=' + pid + ']'),
			len = o(e.elem).find('[data-pid=' + pid + '] .cbx.layui-form-checked').length;
		if(po.length == len || len == 0) {
			var pid = co.data('pid');
			len ? co.find('.cbx').addClass('layui-form-checked') : co.find('.cbx').removeClass('layui-form-checked');
			pid === undefined || this.parents_checkbox(e, pid);
		}
	};
	// 子级反选
	tree.prototype.childs_checkbox = function(e, id, is_checked) {
		var t = this;
		o(e.elem).find('[data-pid=' + id + ']').each(function() {
			var checkbox = o(this).find('.cbx');
			is_checked ? checkbox.addClass('layui-form-checked') : checkbox.removeClass('layui-form-checked');
			t.childs_checkbox(e, o(this).data('id'), is_checked);
		})
	};
	// 点击收起循环隐藏子级元素
	tree.prototype.childs_hide = function(e, id) {
		var t = this;
		this.cache(e, id, false);
		o(e.elem).find('[data-pid=' + id + ']:not(.' + e.hide_class + ')').each(function() {
			var td = o(this).find('[data-down]'),
				i = td.find('i:not(.layui-icon-ok)');
			// 关闭更换小图标
			i.length && i.attr('class', e.icon.close);
			// 隐藏子级
			td.parents(e.elem).find('[data-pid=' + id + ']').addClass(e.hide_class);
			t.childs_hide(e, o(this).data('id'))
		});
	};
	// 重新组合数据,父子级关系跟随
	tree.prototype.data = function(e) {
		var lists = [],
			childs = [];
		o.each(e.data, function(idx, item) {
			lists[item[e.primary_key]] = item;
			if(!childs[item[e.parent_key]]) {
				childs[item[e.parent_key]] = [];
			}
			childs[item[e.parent_key]][item[e.primary_key]] = item;
		});
		e.childs = childs;
		return this.tree_data(e, lists, e.top_value, []);
	};
	tree.prototype.tree_data = function(e, lists, pid, data) {
		if(lists[pid]) {
			data.push(lists[pid]);
			delete lists[pid]
		}
		var t = this;
		o.each(e.data, function(index, item) {
			if(item[e.parent_key] == pid) {
				data.concat(t.tree_data(e, lists, item[e.primary_key], data))
			}
		});
		return data;
	};
	tree.prototype.render = function(e) {
		var treeObj = o(e.elem).data("tree"),option = null;
		if(!treeObj) {
			treeObj = new tree();
			option = this.config();
			o(e.elem).data("tree",treeObj);
		}
		else
		{
			option = treeObj.option;
		}
		e = o.extend(option, e);
		treeObj.option = e;
		if(e.url) {
			if (e.method && e.method.toLowerCase() == "post") {
				o.post(e.url, e.where, function (res) {
					e.data = res;
					treeObj.template(e);
				})
			} else {
				o.get(e.url, e.where, function (res) {
					e.data = res;
					treeObj.template(e);
				})
			}
		} else {
			treeObj.template(e);
		}
		return treeObj;
	};
	// 获取已选值集合
	tree.prototype.checked = function(e) {
		var items = [];
		o(e.elem).find('.cbx.layui-form-checked').each(function() {
			var tr = o(this).parents('[data-id]'),
				id = tr.data('id'),
				pid = tr.data('pid');
			items.push(e.childs[pid][id]);
		});
		return items;
	};
	// 全部展开
	tree.prototype.openAll = function(e) {
		var t = this;
		o.each(e.data, function(idx, item) {
			item[e.primary_key] && t.cache(e, item[e.primary_key], true);
		})
		this.render(e);
	}
	// 全部关闭
	tree.prototype.closeAll = function(e) {
		localStorage.setItem(e.elem.substr(1), '');
		this.render(e);
	}
	tree.prototype.on = function(events, callback) {
		return layui.onevent.call(this, MOD_NAME, events, callback)
	};
	// 存储折叠状态
	tree.prototype.cache = function (e, val, option) {
		if (e.open_all) {
			return true;
		}

		var name = e.elem.substr(1),
			val = val.toString(),
			cache = localStorage.getItem(name) ? localStorage.getItem(name).split(',') : [],
			index = o.inArray(val, cache);
		if (option === undefined) {
			return index > -1;
		}

		if ((option && index > -1) || (!option && index === -1)) {
			return;
		}

		if(option && index == -1) {
			cache.push(val)
		}
		else if(!option && index > -1) {
			cache.splice(index, 1)
		}
		localStorage.setItem(name, cache.join(','));
	};
	tree.prototype.reload = function(id,option) {
		option = option || {};
		option.elem = "#"+id;
		return this.render(option);
	};
	tree.prototype.checkStatus = function(id) {
		var treeObj = o("#" + id).data("tree"),result = {data:[]};
		if(!treeObj)
		{
			return result;
		}
		return {
			data: treeObj.checked(treeObj.option)
		};
	};
	exports(MOD_NAME, new tree())
});

效果:

layui treeTable

今天的文章layui treeTable分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/6031.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注