从json动态构建dom树

时间:2015-02-03 13:16:44

标签: javascript jquery json

这是我的JSON数据。我需要构建一个dom,其中的节点在其子节点内构建。我能够为没有孩子的节点构建一个dom。关于如何使用包含在父级中的子级构建dom树的任何指针都将不胜感激

 {
       "widgetData":[
          {
             "label":"node1",
             "color":"red",
             "children":[
                {
                   "label":"vip1",
                   "color":"red",
                   "children":[
                      {
                         "label":"obj1",
                         "color":"gray",
                         "id":"539803eae4b0ffad82491508"
                      },
                      {
                         "label":"obj2",
                         "color":"green",
                         "id":"5395635ee4b071f136e4b691"
                      },
                      {
                         "label":"obj3",
                         "color":"green",
                         "id":"539803e4e4b0ffad82491507"
                      }
                   ],
                   "id":"53956358e4b071f136e4b690"
                },
                {
                   "label":"vip2",
                   "color":"blue",
                   "id":"539803f2e4b0ffad82491509"
                }
             ],
             "id":"5395634ee4b071f136e4b68e"
          },
          {
             "label":"node2",
             "children":[
                {
                   "label":"vip1",
                   "color":"green",
                   "id":"539803eae4b0ffad82491501"
                },
                {
                   "label":"vip2",
                   "color":"green",
                   "id":"5395635ee4b071f136e4b694"
                }
             ],
             "id":"5395637fe4b071f136e4b692"
          },
          {
             "label":"node3",
             "color":"red",
             "children":[

             ],
             "id":"53956371f136e4b692"
          },
          {
             "label":"node4",
             "color":"red",
             "children":[

             ],
             "id":"5656"
          },
          {
             "label":"node5",
             "color":"red",
             "children":[
             ],
             "id":"5395637fe4b071f13b692"
          }
       ]
    }

我试过的javascript代码

for (var i = 0; i <jsonData.length; i++) {
                    var $divParent  = $("<div></div>");
                    $divParent.text(jsonData[i].label).attr('id',jsonData[i].id);
                    if (jsonData[i].children.length >0 ) {


                    }
                    else {
                        container.append($divParent);
                    }
                }

容器是DIV元素

需要解决我孩子的深度可以增加的问题。

4 个答案:

答案 0 :(得分:4)

你几乎把它钉了下来。你需要的是递归:

function appendDom(container, jsonData) {
    for (var i = 0; i <jsonData.length; i++) {
        var $divParent  = $("<div></div>");
        $divParent.text(jsonData[i].label).attr('id',jsonData[i].id);
        if (jsonData[i].children) {
            appendDom($divParent, jsonData[i].children);
        }
        container.append($divParent);
    }
}

这是一个小提琴:http://jsfiddle.net/robbyn/x15h2g6v/

答案 1 :(得分:2)

调用你的函数递归地追加孩子,如:

function appendChildren(parentEl, children) {
      for (var i = 0; i < children.length; i++) {
        var child = children[i],
            element = $('<div />');
        element.text(child.label).attr(child.id);
        appendChildren(element, child.children);
        parentEl.append(element);
      }
    }

var root = $('body');
appendChildren(root, jsonData);

答案 2 :(得分:1)

您可能需要创建一个属性值函数映射,如下所示:

var map = {
    'label': function(value) { 
        return function(el) { el.text(value); };
    },
    'color': function(value) { 
        return function(el) { el.css('color', value); }; 
    },
    'children': function(items) { 
        return function(el) {
            items.forEach(function(item) { 
                var child = create(item);
                el.append(child);
            });
        };
    }
};

然后你可以创建一个初始化函数:

function create(markup) {
    var el = $('<div>');
    var actions = [];
    for (var key in markup) {
        var value = markup[key];
        var act = map[key](value);
        actions.push(act);
    }
    actions.forEach(function(act) {
        act(el);
    });
    return el;
}

最后致电:

$('body').append(create(markup));

答案 3 :(得分:-1)

这样的东西?

for (var i = 0; i < jsonData.length; i++) {
    // Create parent
    var $divParent  = getHtml(jsonData[i]);

    $divParent.text(jsonData[i].label).attr('id',jsonData[i].id);

    // Check if JSON element has "children" property which is an array and has elements
    if (jsonData[i].children && jsonData[i].children.constructor === Array && jsonData[i].children.length) {
        for (var c = 0; c < jsonData[i].children.length; c++) {
            // Generate child HTML and append to parent
            var childHtml = getHtml(jsonData.children[c]);
            $divParent.Html($divParent.Html() + childHtml);
        }
    }

    container.append($divParent);
}

function getHtml(jsonObject) {
    var $div = $("<div></div>");
    $div.text(jsonObject.label).attr('id', jsonObject.id);
    return $div;
}