前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >layui treeTable「建议收藏」

layui treeTable「建议收藏」

作者头像
全栈程序员站长
发布2022-08-11 21:36:07
9650
发布2022-08-11 21:36:07
举报

大家好,又见面了,我是你们的朋友全栈君。

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

代码语言:javascript
复制
@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

代码语言:javascript
复制
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(日期转换)

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
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://javaforall.cn/131484.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022年4月2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档