0

我想知道是否有一种内置方法可以将如下所示的 JSON 转换为具有 ul 和 li 的树。

示例 JSON:

{
{parent=-1,id=0,name='root'},
{parent=0,id=1,name='x'},
{parent=0,id=2,name='y'},
{parent=1,id=3,name='z'},
{parent=1,id=4,name='w'},
{parent=1,id=5,name='c'},
{parent=2,id=6,name='d'}
}
4

2 回答 2

2

这是一个我故意不解释的函数。

function buildNestedList(treeNodes, rootId) {
  var nodesByParent = {};

  $.each(treeNodes, function(i, node) {
    if (!(node.parent in nodesByParent)) nodesByParent[node.parent] = [];
    nodesByParent[node.parent].push(node);
  });

  function buildTree(children) {
    var $container = $("<ul>");

    if (!children) return;
    $.each(children, function(i, child) {
      $("<li>", {text: child.name})
      .appendTo($container)
      .append( buildTree(nodesByParent[child.id]) );
    });
    return $container;
  }
  return buildTree(nodesByParent[rootId]);
}

它变成了这个

var treeNodes = [
    {parent:-1,id:0,name:'root'},
    {parent:0,id:1,name:'x'},
    {parent:0,id:2,name:'y'},
    {parent:1,id:3,name:'z'},
    {parent:1,id:4,name:'w'},
    {parent:1,id:5,name:'c'},
    {parent:2,id:6,name:'d'}
];

进入这个

<ul>
  <li>x
    <ul>
      <li>z</li>
      <li>w</li>
      <li>c</li>
    </ul>
  </li>
  <li>y
    <ul>
      <li>d</li>
    </ul>
  </li>
</ul>

在这里看到它:http: //jsfiddle.net/Tomalak/uUBKf/

于 2012-08-14T17:26:43.170 回答
0

您可以在上述内部函数的一行中添加超链接:<li>

$("<li><a href ='#'>"+child.name+"</>", {text: child.name})
于 2020-08-04T14:02:01.303 回答