从JSON动态添加DIV

时间:2014-07-24 06:04:20

标签: javascript jquery dynamic tree element

我正在尝试基于JSON文件动态构建树形图。

基本代码如下:

var arrayFinalChartData = [{
    "1": "2",
        "id": "4d344e35-d8b1-49ec-c564-759639816704",
        "parentid": "rootDiv"
}, {
    "3": "4",
        "id": "951de378-b191-498e-b31f-7250e6a7ef1f",
        "parentid": "rootDiv"
}, {
    "OS": "WINDOW",
        "id": "15d332c3-613d-4aee-8d17-b731c682f242",
        "parentid": "951de378-b191-498e-b31f-7250e6a7ef1f"
}];


$('#loadChart').click(function () {
    //console.log("arrayFinalChartData:" + (JSON.stringify(arrayFinalChartData));
    // build chart

    $(arrayFinalChartData).each(function (i, obj) {

        //console.log(arrayFinalChartData[i].id);
        //console.log(arrayFinalChartData[i].parentid);


        //Retrieve the innerHTML

        itemStringDetails = JSON.stringify(obj);
        var mySubString = "";

        for (n = 0; n < 3; n++) {

            var partString = itemStringDetails.split(',')[n];

            console.log("partString :" + partString);

            if ((partString.indexOf('id', 0) == -1) && (partString.indexOf('parentid', 0) == -1)) {

                var mySubString = partString;
                console.log("mySubString :" + mySubString);
            };


        };


        itemHTML = mySubString.replace("{", '');

        console.log("itemHTML:" + itemHTML);  



            $('#buildTree').append('div').addClass("newDIV").attr('id', arrayFinalChartData[i].id).html(itemHTML).data("parentid", arrayFinalChartData[i].parentid);


        //console.log(this.parentid);
    });
});

完整的HTML和JS位于:JS Bin

注意:每个div都有IDParentID。遵循ParentID

的层次结构

所有Div必须保留JSON中的属性,这样当我们保存时,我们会得到相同的Json。请注意&#34; 1&#34;:&#34; 2&#34; .. &#34; 5&#34;:&#34; 6&#34;碰巧是各个Div的innerHTML。内容可以是 - &#34; OS&#34;:&#34; window&#34;。 &#34;版本&#34;:&#34; XP&#34;等等......它将是网络设备的图表

3 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

if (arrayFinalChartData[i].parentid == "rootDiv")
    $("#buildTree").append("<div id='" + arrayFinalChartData[i].id + "'>It's here</div>");
else
    $("#" + arrayFinalChartData[i].parentid)
    .append("<div id='" + arrayFinalChartData[i].id + "'>It's here</div>")

答案 1 :(得分:0)

<!DOCTYPE HTML>
<head>
    <title>Untitled</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="tree"></div>
<script>
    'use strict';

    var data = [{
        "1": "2",
            "id": "4d344e35-d8b1-49ec-c564-759639816704",
            "parentid": "rootDiv"
    }, {
        "3": "4",
            "id": "951de378-b191-498e-b31f-7250e6a7ef1f",
            "parentid": "rootDiv"
    }, {
        "5": "6",
            "id": "15d332c3-613d-4aee-8d17-b731c682f242",
            "parentid": "951de378-b191-498e-b31f-7250e6a7ef1f"
    }],
    root = $(document.getElementById('tree')),
    key,
    tree = {},
    tmp;
    /*
        {
            id1: [array of object woth this parent id],
            id2: ...
        }
    */
    for (key in data) {
        if (data.hasOwnProperty(key)) {
            tmp = data[key];
            if (tree[tmp.parentid] === undefined) {
                tree[tmp.parentid] = [];
            }
            tree[tmp.parentid].push(data[key]);
        }
    }
    console.log(tree);
    //as structure of json is very strange
    function getContent(node) {
        var key;
        for (key in node) {
            return node[key];
        }
    }

    function recBuild(tree, seed) {
        var i, 
            arr = tree[seed],
            len = arr.length,
            //output html is a array of chars. That is the fastest way
            //to concatenate strings
            frag = [];
        for (i = 0; i < len; i++) {
            //make sequence of divs with current parent id
            frag.push("<div id='" + arr[i].id + "'>" + getContent(arr[i]));
            //if current id is someone's parent id, then make subtree
            if (tree[arr[i].id] !== undefined) {
                frag.push(recBuild(tree, arr[i].id));
            }
            frag.push("</div>");
        }
        //convert array to string
        return frag.join('');
    }

    root.append(recBuild(tree, 'rootDiv'));
</script>
</body>
</html>

UPD:如果想逐级更改保证金

function recBuild(tree, seed, level) {
        var i, 
            arr = tree[seed],
            len = arr.length,
            //output html is a array of chars. That is the fastest way
            //to concatenate strings
            frag = [];
        for (i = 0; i < len; i++) {
            //make sequence of divs with current parent id
            frag.push("<div style='margin-left:" + (level*10) + "px' id='" + arr[i].id + "'>" + getContent(arr[i]));
            //if current id is someone's parent id, then make subtree
            if (tree[arr[i].id] !== undefined) {
                frag.push(recBuild(tree, arr[i].id, level + 1));
            }
            frag.push("</div>");
        }
        //convert array to string
        return frag.join('');
    }

    root.append(recBuild(tree, 'rootDiv', 0));

没有jquery的Upd2

'use strict';

var data = [{
    "1": "2",
        "id": "4d344e35-d8b1-49ec-c564-759639816704",
        "parentid": "rootDiv"
}, {
    "3": "4",
        "id": "951de378-b191-498e-b31f-7250e6a7ef1f",
        "parentid": "rootDiv"
}, {
    "5": "6",
        "id": "15d332c3-613d-4aee-8d17-b731c682f242",
        "parentid": "951de378-b191-498e-b31f-7250e6a7ef1f"
}],
root = document.getElementById('tree'),
key,
tree = {},
tmp;
/*
    {
        id1: [array of object woth this parent id],
        id2: ...
    }
*/
for (key in data) {
    if (data.hasOwnProperty(key)) {
        tmp = data[key];
        if (tree[tmp.parentid] === undefined) {
            tree[tmp.parentid] = [];
        }
        tree[tmp.parentid].push(data[key]);
    }
}
console.log(tree);
//as structure of json is very strange
function getContent(node) {
    var key;
    for (key in node) {
        return node[key];
    }
}

function recBuild(tree, seed, level) {
    var i, 
        arr = tree[seed],
        len = arr.length,
        //output html is a array of chars. That is the fastest way
        //to concatenate strings
        frag = [];
    for (i = 0; i < len; i++) {
        //make sequence of divs with current parent id
        frag.push("<div style='margin-left:" + (level*10) + "px' id='" + arr[i].id + "'>" + getContent(arr[i]));
        //if current id is someone's parent id, then make subtree
        if (tree[arr[i].id] !== undefined) {
            frag.push(recBuild(tree, arr[i].id, level + 1));
        }
        frag.push("</div>");
    }
    //convert array to string
    return frag.join('');
}

root.innerHTML = (recBuild(tree, 'rootDiv', 0));

使用jQuery的递归解决方案。进一步提问

答案 2 :(得分:0)

尝试此解决方案:http://fiddle.jshell.net/qZGVk/1/

$('#loadChart').click(function () {
  var i = arrayFinalChartData.length;
var counter = 0;
$(arrayFinalChartData).each(function (i, obj) {

    if(obj.parentid === "rootDiv"){
        $('#buildTree').append('<div id="'+obj.id+'" parentid ="'+obj.parentid+'">Parent id:'+obj.parentid+'</div>');
    }
    counter++;
});
 if(counter === i){
 $(arrayFinalChartData).each(function (i, obj) {
if(obj.parentid !== "rootDiv"){

var result = $.grep(arrayFinalChartData, function(e){ return obj.parentid == e.id; });

       if (typeof result !== 'undefined' && result.length > 0) {
            $('#'+result[0].id+'').append('<div id="'+obj.id+'" parentid ="'+obj.parentid+'">Child id:'+obj.id+'</div>');
        }
    else{
        alert("no existing parent");
    }


}

});
      }

});