基于jquery的树列表选择插件 JqTree.js

效果图:

css样式

*{
    margin: 0px;
    padding: 0px;
}
.ul_tree{
    list-style: none;
}
.ul_tree .sub_li{
    border-bottom: none;
    padding-left: 0px !important;
}
.ul_tree li{
    list-style: none;
    min-height: 40px;
    height: auto;
    line-height: 40px;
    padding-left: 30px;
    border-bottom: 1px solid #E5E5E5;
    font-size: 18px;
}
.ul_tree li input{
    margin-right: 5px;
}

.ul_tree .open {
    background-image: url('/content/img/tree_open.png') ;
    background-repeat: no-repeat;
    background-size: 20px 15px;
    background-position:5px 12.5px;
}
.ul_tree .close{
    background-image: url('/content/img/tree_close.png') ;
    background-repeat: no-repeat;
    background-size: 10px 20px;
    background-position:10px 10px;
}
.ul_tree .act_li{
    background-color: #E5E5E5;
    border-color: #ddd;
}
/* 树级别 从0级开始*/
/* 第1级 */
.ul_tree .tree_level_1 li{
    padding-left: 40px;
}
.ul_tree .tree_level_1 .open{
    background-position:15px 12.5px;
}
.ul_tree .tree_level_1 .close{
    background-position:20px 10px;
}
/* 第2级 */
.ul_tree .tree_level_2 li{
    padding-left: 50px;
}
.ul_tree .tree_level_2 .open{
    background-position:25px 12.5px;
}
.ul_tree .tree_level_2 .close{
    background-position:30px 10px;
}
/* 第3级 */
.ul_tree .tree_level_3 li{
    padding-left: 60px;
}
.ul_tree .tree_level_3 .open{
    background-position:35px 12.5px;
}
.ul_tree .tree_level_3 .close{
    background-position:40px 10px;
}
/* 第4级 */
.ul_tree .tree_level_4 li{
    padding-left: 70px;
}
.ul_tree .tree_level_4 .open{
    background-position:45px 12.5px;
}
.ul_tree .tree_level_4 .close{
    background-position:50px 10px;
}
/* 第5级 */
.ul_tree .tree_level_5 li{
    padding-left: 80px;
}
.ul_tree .tree_level_5 .open{
    background-position:55px 12.5px;
}
.ul_tree .tree_level_5 .close{
    background-position:60px 10px;
}
/* 第6级 */
.ul_tree .tree_level_6 li{
    padding-left: 90px;
}
.ul_tree .tree_level_6 .open{
    background-position:65px 12.5px;
}
.ul_tree .tree_level_6 .close{
    background-position:70px 10px;
}
/* 第7级 */
.ul_tree .tree_level_7 li{
    padding-left: 100px;
}
.ul_tree .tree_level_7 .open{
    background-position:75px 12.5px;
}
.ul_tree .tree_level_7 .close{
    background-position:80px 10px;
}
/* 第8级 */
.ul_tree .tree_level_8 li{
    padding-left: 110px;
}
.ul_tree .tree_level_8 .open{
    background-position:85px 12.5px;
}
.ul_tree .tree_level_8 .close{
    background-position:90px 10px;
}
tree.css

JS

$.fn.JqTreeInit = function (data, options, callback) {
    var JqTree = {
        target: null,
        sourcedata: null,
        init: function (data, options) {
            this.sourcedata = data;
            //处理参数
            this.options = $.extend({}, this.defaults, options || {});
            //初始化数据
            this.initData(data);
            //注册单击事件
            this.registerTreeClick();
            //回调方法
            if (callback) {
                callback(this)
            }
        },
        initData: function (data) {
            //构建树结构
            var treeData = this.getTreeData(data, this.options.topPid);
            //生成树
            var treeHtml = this.generateTreeHtml(treeData, 1);
            $(this.target).html(treeHtml)
        },
        getTreeData: function (data, pid) {
            var obj = this;
            var result = [];
            $(data).each(function (i, item) {
                if (item[obj.options.pIdName] == pid) {
                    result.push({
                        id: item[obj.options.idName],
                        pid: item[obj.options.pIdName],
                        name: item[obj.options.nameName],
                        children: obj.getTreeData(data, item[obj.options.idName])
                    });
                }
            });
            return result;
        },
        generateTreeHtml: function (data, level) {
            var obj = this;
            var result = "";
            $(data).each(function (i, item) {
                var id = item.id;
                var name = item.name;
                var className = "open";
                if (item.children.length == 0) {
                    className = "last";
                }
                else if (obj.options.expandLevel > 0 && level > obj.options.expandLevel) {
                    className = "close";
                }
                result += '<li id="' + id + '" class="' + className + '"><input type="checkbox" />' + name + '</li>';
                if (item.children.length > 0) {
                    result += '<li pid="' + id + '" class="sub_li" ' + (className == "close" ? "hidden" : "") + '>';
                    result += '<ul class="tree_level_' + (level) + '">';
                    result += obj.generateTreeHtml(item.children, level + 1);
                    result += '</ul></li>';
                }
            });
            return result;
        },
        //注册树单击事件
        registerTreeClick: function () {
            var obj = this;
            var parentBox = obj.target;
            $(parentBox).find("li").not(".sub_li").each(function (i, li) {
                //行单击事件
                $(li).click(function () {
                    var id = $(this).attr("id");
                    var isopen = $(this).is(".open");
                    var subli = $(parentBox).find("li[pid='" + id + "']");
                    if (subli.length > 0) {
                        if (isopen) {
                            $(parentBox).find("li[pid='" + id + "']").hide();
                            $(this).removeClass("open").addClass("close");
                        }
                        else {
                            $(parentBox).find("li[pid='" + id + "']").show();
                            $(this).removeClass("close").addClass("open");
                        }
                    }
                    //最后一级
                    if($(this).is(".last")){
                        $(this).find("input[type='checkbox']").click();
                    }
                });
                //复选框单击事件
                $(li).find("input[type='checkbox']").click(function (e) {
                    var id = $(this).parent().attr("id");
                    var ischecked = $(this).is(":checked");
                    //单选
                    if (obj.options.single) {
                        if (ischecked) {
                            $(parentBox).find("input[type='checkbox']").prop("checked", false);
                            $(this).prop("checked", true);
                        }
                    }
                    //复选
                    else {
                        //选中状态
                        if (ischecked) {
                            //正向联动
                            $(parentBox).find("li[pid='" + id + "'] input[type='checkbox']").prop("checked", true);
                        }
                        else {
                            //正向联动
                            $(parentBox).find("li[pid='" + id + "'] input[type='checkbox']").prop("checked", false);
                        }
                        //反向联动
                        obj.checkboxReverseLinkage(this, ischecked)
                    }
                    //设置li选中状态
                    obj.setLiAct();
                    //阻止事件冒泡
                    if (e && e.stopPropagation) {//非IE
                        e.stopPropagation();
                    }
                    else {//IE
                        window.event.cancelBubble = true;
                    }
                });
            });
        },
        //反向联动
        checkboxReverseLinkage: function (checkbox, ischecked) {
            var parentBox = this.target;
            var parentSubLi = $(checkbox).parent().parent().parent();
            if (parentSubLi != undefined && parentSubLi != null && parentSubLi.length > 0) {
                var subliCheckBox = $(parentBox).find("li[id='" + $(parentSubLi).attr("pid") + "'] input[type='checkbox']");
                if (ischecked) {
                    //反向联动
                    if ($(parentSubLi).find("input[type='checkbox']").not(":checked").length == 0) {
                        $(subliCheckBox).prop("checked", true);
                    }
                }
                else {
                    //反向联动
                    if ($(parentSubLi).find("input[type='checkbox']").not(":checked").length > 0) {
                        $(subliCheckBox).prop("checked", false);
                    }
                }
                this.checkboxReverseLinkage(subliCheckBox, ischecked);
            }
        },
        setLiAct: function () {
            var parentBox = this.target;
            $(parentBox).find("li").removeClass("act_li");
            $(parentBox).find("input[type='checkbox']:checked").parent().addClass("act_li");
        },
        //获取选中值
        getCheckedDatas: function () {
            var obj = this;
            var parentBox = this.target;
            var ids = new Array();
            $(parentBox).find(".act_li").each(function () {
                ids.push($(this).attr("id"));
            });
            var result = [];
            $(this.sourcedata).each(function () {
                if (ids.indexOf(this[obj.options.idName] + "") > -1) {
                    result.push(this)
                }
            });
            if (obj.options.single) {
                return result.length == 0 ? null : result[0]
            }
            else {
                return result.length == 0 ? null : result;
            }
        },
        getDataById: function (id) {
            var obj = this;
            var result = null;
            $(this.sourcedata).each(function () {
                if ((this[obj.options.idName] + "") === (id + "")) {
                    result = this;
                    return result;
                }
            });
            return result;
        },
        //默认参数 如需指定新的值,请在调用处指定
        defaults: {
            single: true,//是否单选
            idName: "id",//id对应的属性名称
            nameName: "name",//name对应的属性名称
            pIdName: "parentId",//pId对应的属性名称
            topPid: 0,//最上级的pid对应的值
            expandLevel: 1  //默认展开级别  0-全部展开
        },
        //实际参数
        options: {}
    }
    JqTree.target = this;
    JqTree.init(data, options);
    return JqTree;
}
tree.js

调用

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>树形列表选择</title>
    <script src="/content/jquery/jquery.1.12.4.min.js"></script>

    <link href="/content/jqueryTree/tree.css" rel="stylesheet" />
    <script src="/content/jqueryTree/tree.js"></script>
</head>

<body>
    <input type="button" value="获取选中值" onclick="BringBack()" />
    <ul class="ul_tree" id="ulTree">

    </ul>
</body>

</html>
<script>
    var JqTreeObj = null;
    $(function () {
        //树形数据
        var data = [
            {
                id: 1,
                name: "一级标题-1",
                pId: 0,
                otherProperty1: "其他属性1",
                otherProperty2: "其他属性2",
                otherProperty3: "其他属性3"
            },
            {
                id: 2,
                name: "二级标题-1-1",
                pId: 1,
                otherProperty1: "其他属性1",
                otherProperty2: "其他属性2",
                otherProperty3: "其他属性3"
            },
            {
                id: 3,
                name: "二级标题-1-2",
                pId: 1,
                otherProperty1: "其他属性1",
                otherProperty2: "其他属性2",
                otherProperty3: "其他属性3"
            },
            {
                id: 4,
                name: "二级标题-1-3",
                pId: 1,
                otherProperty1: "其他属性1",
                otherProperty2: "其他属性2",
                otherProperty3: "其他属性3"
            },
            {
                id: 5,
                name: "一级标题-2",
                pId: 0,
                otherProperty1: "其他属性1",
                otherProperty2: "其他属性2",
                otherProperty3: "其他属性3"
            },
            {
                id: 6,
                name: "二级标题-2-1",
                pId: 5,
                otherProperty1: "其他属性1",
                otherProperty2: "其他属性2",
                otherProperty3: "其他属性3"
            },
            {
                id: 7,
                name: "二级标题-2-2",
                pId: 5,
                otherProperty1: "其他属性1",
                otherProperty2: "其他属性2",
                otherProperty3: "其他属性3"
            },
            {
                id: 8,
                name: "二级标题-2-3",
                pId: 5,
                otherProperty1: "其他属性1",
                otherProperty2: "其他属性2",
                otherProperty3: "其他属性3"
            },
            {
                id: 9,
                name: "三级标题-1-1-1",
                pId: 2,
                otherProperty1: "其他属性1",
                otherProperty2: "其他属性2",
                otherProperty3: "其他属性3"
            },
            {
                id: 10,
                name: "三级标题-1-1-2",
                pId: 2,
                otherProperty1: "其他属性1",
                otherProperty2: "其他属性2",
                otherProperty3: "其他属性3"
            }
        ];
        //构建树
        JqTreeObj = $("#ulTree").JqTreeInit(data,
            {
                pIdName: "pId", //此处指定父级id的属性名称
                single: false,  //此处指定是否单选  false-多选
                expandLevel: 0  //此处指定展开级别 0-全部展开
                //其他参数 根据实际情况指定
            },
            function (JqTreeObj) {
                //回调函数 此处添加特殊的逻辑 JqTreeObj为树对象
            });
    });
    function BringBack() {
        //获取选中值
        var data = JqTreeObj.getCheckedDatas();
        alert(JSON.stringify(data))
    }
</script>
demo.html

 附件:

      

注:以上代码属个人整理,用于交流学习。(QQ/微信:742010299 昵称:同心同德)

posted @ 2020-07-31 18:49  同心同德  阅读(302)  评论(0编辑  收藏  举报