jquery使用递归制作树形菜单

效果:

    let jsonDatas = [
        {
            name: "一级1",
            children: [
                {
                    name: "二级1-1",
                    children: [
                        {
                            name: "三级1-1-1",
                            children: [
                                {
                                    name: "四级1-1-1-1",
                                }
                            ]
                        }
                    ]
                },
                {
                    name: "二级1-2"
                },
                {
                    name: "二级1-3"
                }
            ]
        },
        {
            name: "一级2",
            children: [
                {
                    name: "二级2-1"
                },
                {
                    name: "二级2-2"
                },
                {
                    name: "二级2-3"
                }
            ]
        }
    ];
    let tree = 0;
    function RecursiveTree(datas,isRoot,index,id) {
        for(let i in datas) {
            tree++;
            let rootDom = '<div id="tree'+tree+'">'+datas[i].name+'</div>';
            datas[i].id = tree;
            if(isRoot == "root") {
                index = 0;
                id = -1;
                $(".tree").append(rootDom);
            }
            else {
                $('#tree'+id).append(rootDom)
                $('#tree'+tree).addClass("paddingLeft20");
                $('#tree'+tree).addClass("notRoot");
                $('#tree'+tree).addClass("displayNone");
            }
            if(typeof datas[i].children != "undefined" && datas[i].children.length>0) {
                $('#tree'+tree).prepend('<svg class="icon isSpreadIcon" aria-hidden="true">\n' +
                    '    <use xlink:href="#icon-jiantouyou"></use>\n' +
                    '</svg>')
                index++;
                RecursiveTree(datas[i].children,'notRoot',index,datas[i].id);
            }
        }

    }
    RecursiveTree(jsonDatas,"root",0);

    $(".isSpreadIcon").click(function () {
        let index = $(this).index() - 1;
        let parent = $(this).eq(index).parent();
        let children = $(parent).children('.notRoot');
        for(child of children) {
            $(child).toggleClass("displayNone");
        }
        let classIsNone=$(children).hasClass("displayNone");
        if(classIsNone) {
            $(this).find('use')[0].href.baseVal = "#icon-jiantouyou";
        }
        else {
            $(this).find('use')[0].href.baseVal = "#icon-jiantouxia";
        }
    })
发布了111 篇原创文章 · 获赞 19 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_34607371/article/details/102607855
今日推荐