jquery 树状结构插件手写

此插件依赖于jquery 并且插件内图标依赖于https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css
js如下

(function($){
    'use strict';
    function Trees(element,options){
        this.element = element;
        this.options = {
            array:options.array,//trees结构数组
            nodeName:options.nodeName,//子结构参数名
            isCheckbox:options.isCheckbox,//是否使用多选框,
            deep:0
        };
        this.init();
    };

    Trees.prototype = {
        constructor:Trees,
        init:function(){
            this.createHtml();
            this.bindClickEvent();
        },
        createHtml:function(){
            console.log(this.options);
            this.loop(this.options.array,undefined,this.options.deep);
        },
        bindClickEvent:function(){
            $(document).on("click",".treesNode",function(e){
                e.stopPropagation();
                $(".treesNode").removeClass("currentNode");
                $(this).addClass("currentNode");
            });
            $(document).on("click",".toggleChildrenNode",function(e){
                $(this).toggleClass("fa-caret-left");
                $(this).toggleClass("fa-caret-down");
                $(this).parent().parent().find(".childrens").eq(0).toggle()
            });
        },
        loop:function(array,id,deep){
            console.log(id)
            deep++;
            array.forEach(item=>{
                let html = `
                
  • ${this.isCheckboxFun(item)} ${item.name}
  • `; if(id){ $(`.childrens[data-id=${id}]`).append(html); } else { this.element.append(html); }; if(item[this.options.nodeName] && item[this.options.nodeName].length != 0){ this.loop(item[this.options.nodeName],item.id,deep) } }) }, isCheckboxFun:function(item){ if(this.options.isCheckbox){ return `` } else { return "" } } }; $.fn.trees = function (options) { return new Trees($(this), options); } })($)

    css

    .treesNode {
        list-style: none;
    }
    

    使用方法

    //#trees为需要生成树状结构的dom 变量tree为数据结构 
    $("#trees").trees({
            array:tree,
            nodeName:"children",
            isCheckbox:true,
        });
    

    最终结果


    image.png

    你可能感兴趣的:(jquery 树状结构插件手写)