任意深度的嵌套列表

任意深度的嵌套列表

假设我有以下JSON数组:

tree = [{
    name: "A",
    children: [{
        name: "AA",
        children: []
    }, {
        name: "AB",
        children: []
    }]
}, {
    name: "B",
    children: [{
        name: "BA",
        children: []
    }, {
        name: "BB",
        children: []
    }]
}]


此外,假设我要构造以下HTML:

<ul>
    <li>
        <label>A</label>
        <ul>
            <li>
                <label>AA</label>
                <ul></ul>
            </li>
            <li>
                <label>AB</label>
                <ul></ul>
            </li>
        </ul>
    </li>
    <li>
        <label>B</label>
        <ul>
            <li>
                <label>BA</label>
                <ul></ul>
            </li>
            <li>
                <label>BB</label>
                <ul></ul>
            </li>
        </ul>
    </li>
</ul>


我可以使用Knockout做到这一点,如下所示:

<ul data-bind="foreach: tree">
    <li>
        <label data-bind="text: name"></label>
        <ul data-bind="foreach: children">
            <li>
                <label data-bind="text: name"></label>
                <ul></ul>
            </li>
        </ul>
    </li>
</ul>


但是,这不适用于任意深度的嵌套列表。我能做什么?

最佳答案

使用递归template,例如像这样:



var tree = {
  subItems: [
    {
      name: "A",
      subItems: [ { name:"AA", subItems: [] }, { name:"AB", subItems: [] }, { name:"AC", subItems: [] } ]
    },
    {
      name: "B",
      subItems: [ { name:"BA", subItems: [] }, { name:"BB", subItems: [{name:"BB1 (etc)", subItems: []}] } ]
    }
  ]
};

ko.applyBindings(tree);

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<script type="text/html" id="myTemplate">
    <ul data-bind="foreach: $data">
        <li>
            <label data-bind="text: name"></label>
            <div data-bind="template: { name: 'myTemplate', data: subItems }"></div>
        </li>
    </ul>
</script>

<div data-bind="template: { name: 'myTemplate', data: $root.subItems }"></div>

关于javascript - 如何呈现任意深度的嵌套列表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26048987/

10-13 01:44