简体   繁体   中英

How do I create a nested ordered list in HTML

What's the best way to create a nested list like this one from nested JSON objects (by list, I mean the < ol > tag or something custom with similar behaviour):

  1. Parent 1
    a. Sub 1
    b. Sub 2
    i.Sub Sub 1
    ii.Sub Sub 2
    c. Sub 3
  2. Parent 2

As an example let's use a limit of maximum 3 "nesting levels" deep.

The JSON object that would generate this list would look like this:

[
     {
         "content": "Parent 1",
         "children": [
             {
                 "content": "Sub 1",
                 "children": [...]
             },
             {
                 "content": "Sub 2",
                 "children": [...]
             }
         ]

     },
     {
         "content": "Parent 2"
     }
]

try this simplest approach

 var obj = [{ "content": "Parent 1", "children": [{ "content": "Sub 1", "children": [{ "content": "sub sub 12" }] }, { "content": "Sub 2", "children": [{ "content": "sub sub 12" }] }] }, { "content": "Parent 2" }]; var html = getListHTML(obj); console.log( html ); $( "body" ).append( html ); function getListHTML(obj) { if ( !obj ) { return ""; } var html = "<ol>"; html += obj.map(function(innerObj) { return "<li>" + innerObj.content + "</li>" + getListHTML(innerObj.children) }).join(""); html += "</ol>"; return html; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

You can then give a different starting value ( 1 or a or i ) based on the hierarchy level of li

This is a proposal with an iterative and recursive callback for Array#forEach and with proper element generating on the fly.

 function getValues(el) { var li = document.createElement('li'), ol; li.appendChild(document.createTextNode(el.content)); if (Array.isArray(el.children)) { ol = document.createElement('ol'); el.children.forEach(getValues, ol); li.appendChild(ol); } this.appendChild(li); } var data = [{ content: 'Parent 1', children: [{ content: 'Sub 1', children: [] }, { content: 'Sub 2', children: [{ content: 'Sub Sub 1' }, { content: 'Sub Sub 2' }, ] }, { content: 'Sub 3' }] }, { content: 'Parent 2' }], ol = document.createElement('ol'); data.forEach(getValues, ol); document.body.appendChild(ol); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM