1

n-ary ツリー構造をブラウザに表示しようとしています。

以下は、それが引き出されているデータ構造の例です。

var jsonObj = [{
    id: "window1", 
    name: "Corporate",
    children: [
        { id: "window12", name:"IT", children: [
            { id: "window121", name:"Dev", children: [] },
            { id: "window122", name:"Web", children: [] }
        ] }, 
        { id: "window13", name:"HR", children: [] }, 
        { id: "window14", name:"Finance", children: [] }
    ]
}];

私はそれ (構造、つまり) を次のツリーのようにするつもりです (側面のみ):

http://gravite.labri.fr/images/tidyTree.jpg

現在、http://imm.io/Dz3Vに近いように見えますが、それほどではありません。

その出力を生成するために私が書いたアルゴリズムは次のとおりです。

var create_graph_components = function (json, level, offset) {
    for (var i = 0; i < json.children.length; i++) {
        offset += create_graph_components(json.children[i], level + 1, offset);
    }
    if (json.children.length == 0) {
        $('#wrapper').append("<div class=\"component window\" style=\"top:"+offset+"px;left: "+level*150+"px\" id=\""+json.id+"\"><strong>"+json.name+"</strong></div>");
        offset = 50;
    } else {
        $('#wrapper').append("<div class=\"component window\" style=\"top:"+offset/2+"px;left: "+level*150+"px\" id=\""+json.id+"\"><strong>"+json.name+"</strong></div>");
    }
    return offset;
};

それは、ページの正しい位置に div を追加することだけです。これは私が問題を抱えていることです。

アルゴリズムを改善して、ツリーを希望どおりにきれいに印刷する方法を知っている人はいますか?私は近いと思いますが、アイデアを失いました!

4

2 に答える 2

1

以下はどうでしょうか...

function create_graph_components(json, level, offsetStart) {

    var offsetEnd = offsetStart;

    for (var i = 0; i < json.children.length; i++) {
        offsetEnd = create_graph_components(json.children[i], level + 1, offsetEnd);
    }

    var offset;            
    if (json.children.length == 0) {
        offset = offsetEnd;            
        // Node is a leaf therefore extend offsetEnd
        offsetEnd += 50;
    } else {
        // Calculates position halfway between child nodes
        offset = offsetStart + (offsetEnd - offsetStart - 50) / 2;
        // Node is a branch therefore we do not extend the offsetEnd
    }

    // Create the element
    var child = $('<div id="' + json.id + '" class="component window">' +
                      '<strong>' + json.name + '</strong>' +
                  '</div>');

    // Position the element
    child.css({
        top: offset + "px",
        left: level * 150 + "px"
    });

    // Add it to the wrapper
    $("#wrapper").append(child);     

    return offsetEnd;

}

私もフィドルを作成しましたhttp://jsfiddle.net/j7Pms/

于 2012-09-08T02:35:20.623 に答える