如何从 JSON object 递归添加 HTML 元素?

How to recursively add HTML elements from a JSON object?

我有一个 JSON object 未知大小、键数和深度级别。 示例:

{
  "domains": [
    {
      "url_part": "domainOne.com",
      "children": [
        {
          "url_part": "one",
          "children": [
            {
              "url_part": "a",
              "children": [
                {
                  "url_part": "page1",
                  "children": []
                },
                {
                  "url_part": "page2",
                  "children": []
                }
              ]
            },
            {
              "url_part": "b",
              "children": []
            },
            {
              "url_part": "c",
              "children": []
            }
          ]
        },
        {
          "url_part": "two",
          "children": [
            {
              "url_part": "a",
              "children": [
                {
                  "url_part": "page1",
                  "children": []
                },
                {
                  "url_part": "page2",
                  "children": []
                }
              ]
            }
          ]
        }
      ]
    },
    {
      "url_part": "domainTwo.com",
      "children": []
    }
  ]
}

我想要一个页面,最初每个域只有一个按钮,然后当您单击每个按钮时,它会向下扩展一层:

domainOne.com

domainTwo.com

当你点击DomainOne.com变成:

domainOne.com

--一个

--两个

domainTwo.com

我能够为每个域创建一个按钮,但是在为 children.

制作按钮时我只能降低一级

我正在传递:

我尝试递归使用的函数如下所示:

function childrenButtons(parentJSON, level, currentURL, aboveDiv){
                if (parentJSON["children"] == "[]") {
                    //if the JSON you are passing in doesnt have children, this is the end
                    console.log("+++++++++no more kids to show++++++++++++");
                    return 0;
                }
                else {
                 
                    
                    for (let j = 0; j < parentJSON["children"].length; j++) {

                        button.addEventListener("click", function () {
                            ////for each child, create their own div
                            const childDivElement = document.createElement("div");
                            const domainDivElementID = "childDivElement" + j;
                            childDivElement.setAttribute("id", domainDivElementID);
                            aboveDiv.append(childDivElement);

                            //create and add button with name = full path of button
                            const button = document.createElement("button");
                            const currChild = domains[i]["children"][j]["url_part"];
                            fullURL = currentURL + "/" + currChild;
                            button.innerHTML = fullURL;
                            button.style.marginLeft = level*20;
                            childDivElement.append(button);

                            let newParentJSON = parentJSON["children"][j]
                            console.log(parentJSON["children"][j]);

                            treeLevel++;
                            return childrenButtons(newParentJSON, treeLevel, fullURL, childDivElement);

                        }, false);
                    }
                }
            }

你可以通过事件委托来做到这一点...

const data = 
  { domains: 
    [ { url_part: 'domainOne.com', children:
        [ { url_part: 'one', children: 
            [ { url_part: 'a', children:
                [ { url_part: 'page1', children: [] } 
                , { url_part: 'page2', children: [] } 
              ] } 
            , { url_part: 'b', children: [] } 
            , { url_part: 'c', children: [] } 
          ] } 
        , { url_part: 'two', children: 
            [ { url_part: 'a', children: 
                [ { url_part: 'page1', children: [] } 
                , { url_part: 'page2', children: [] } 
      ] } ] } ] } 
    , { url_part: 'domainTwo.com', children: [] } 
  ] } 

const eDomains = document.querySelector('#domains-div')

addButtons( data.domains, eDomains, '' )

eDomains.onclick = evt =>
  {
  if (!evt.target.matches('button')) return

  console.clear()
  console.log( evt.target.textContent )
  }

function addButtons( jsoList, elm, path )
  {
  let UL = elm.appendChild(document.createElement('ul'))

  for ( let {url_part,children } of jsoList )
    {
    let LI = UL.appendChild( document.createElement('li'))
    LI.appendChild( document.createElement('button')).textContent = path + url_part 
    if (children.length > 0)
      addButtons( children, LI, path + url_part + '/')
    }
  }
ul { list-style: none; padding-left: 1em; }
button { min-width: 6em; margin: .1em 0; text-align: left; }
<div id="domains-div"></div>