使用JavaScript创建菜单树?

时间:2019-03-11 07:50:31

标签: javascript arrays

我需要从创建树结构菜单。分隔的字符串数组。

我的输出应该像下面的

        A
            A1
                A2
                A3
            B1
            B2
        B
            B1
                B2
                B3
                    B4
        C
            C1
                C2
        C4

我正在尝试通过以下脚本来实现

        <script>
            function fnAppend(param) {
                var  cWin=window.open("","Categories","width=600,height=800,scrollbars=yes");
                var array = ['A.A1.A2', 'A.A1.A3', 'A.B1.B2','C.C1.C2','B.B1.B2','B.B1.B3.B4','C4'],
                tree = [],
                levels = [tree],
                last = [];

                array.forEach(s => {
                    var temp = s.split('.');
                    temp.forEach((name, i) => {
                        if (last[i] === name) return;        
                        levels[i].push({ name, children: levels[i + 1] = [] });
                    });
                    last = temp;
                });

                function traverse(arr) {
                    for (const branch of arr) {
                        console.log('Mother:', branch.name);
                        var ul=document.createElement('ul');
                        var li=document.createElement('li');
                        li.innerHTML="<a href=''>"+branch.name+"</a>";
                        ul.appendChild(li);
                        if (Array.isArray(branch.children) && branch.children.length > 0) {
                            console.log('Children:', branch.children.map(i => i.name).join(', '));
                            traverse(branch.children);
                        }
                    }
                    var list = document.createElement('div');
                    list.appendChild(ul);
                    try {
                        cWin.document.body.appendChild(list);
                    } catch (err) {
                        if (list.outerHTML) {
                            cWin.document.body.innerHTML = list.outerHTML;
                        } else {
                            console.log(err.name);
                        }
                    }
                }
                traverse(tree);
            }
        </script>
        </head>

        <body>
            <ul id="mylist">

            </ul>
            <input type="button" value="Append child" onclick="fnAppend('test')" />
        </body>

使用上面的脚本,我得到以下输出

A3
B2
B1
C2
C1
B4
B3
B1
C4

请帮助我格式化输出。 预先非常感谢。

关于, 潘卡(Pankaj)

1 个答案:

答案 0 :(得分:0)

您可以创建树并构建包含项目的嵌套列表。

let choose (f: 'K * 'V -> ('K * 'U) option) (e : Series<'K,'V>) =
        e |> Series.map (fun k v -> k, v)
          |> Series.values
          |> (Seq.choose f)
          |> Series.ofValues
          |> Series.map (fun _ v -> snd v)
          |> Series.indexWith (e |> Series.keys)

只有在允许弹出窗口时,另一种方法才有效。

function buildList(tree, target) {
    var ul = document.createElement('ul');
    tree.forEach(node => {
        var li = document.createElement('li');
        li.appendChild(document.createTextNode(node.name));
        node.children.length && buildList(node.children, li);
        ul.appendChild(li);
    });
    target.appendChild(ul);
}


var array = ['A.A1.A2', 'A.A1.A3', 'A.B1.B2','C.C1.C2','B.B1.B2','B.B1.B3.B4','C4'],
    tree = [];

array.forEach(s => s.split('.').reduce((t, name) => {
    var temp = t.find(o => o.name === name);
    if (!temp) {
        t.push(temp = { name, children: [] });
    }
    return temp.children;
}, tree));

console.log(tree);

buildList(tree, document.body);
function open() {
    var cWin = window.open("", "Categories", "width=600,height=800,scrollbars=yes");

    cWin.document.write(buildList(tree).outerHTML);
}

function buildList(tree) {
    if (!tree.length) return;
    var ul = document.createElement('ul');
    tree.forEach(node => {
        var li = document.createElement('li'),
            children = buildList(node.children);
        li.appendChild(document.createTextNode(node.name));
        if (children) li.appendChild(children);
        ul.appendChild(li);
    });
    return ul;
}


var array = ['A.A1.A2', 'A.A1.A3', 'A.B1.B2','C.C1.C2','B.B1.B2','B.B1.B3.B4','C4'],
    tree = [];

array.forEach(s => s.split('.').reduce((t, name) => {
    var temp = t.find(o => o.name === name);
    if (!temp) {
        t.push(temp = { name, children: [] });
    }
    return temp.children;
}, tree));

console.log(tree);