@miroshnik
android/java dev

D3JS. Динамическое добавление узлов в дереве?

Это мое первое знакомство с js и с библиотекой d3js, так что не кидайте помидоры =)
Мне нужно, чтобы по клику по узлу дерева, к кликнутому узлу добавлялся дочерний узел.
Проблема, как я понимаю, в свойстве узла depth и координатах, но как эту проблему решить пока не знаю...

Ссылка на код: jsfiddle.net/EGnNZ/1

Сам код:
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <style type="text/css">
        body {
            background-color: #272822;
        }

        .node circle {
            cursor: pointer;
            fill : #83AF9B;
            stroke: black;
            stroke-width: 2px;
        }

        .node text {
            font: 13px sans-serif;
            color: #ffffff;
            fill: lightgrey;
        }

        .link {
            fill: none;
            stroke: #ccc;
            stroke-width: 2px;
        }
    </style>
    <title></title>
</head>
<body>
<script>

var treeData = [
    {
        "name": "Top Level",
        "weight": -1,
        "status" : -1,
        "parent": "null",
        "children": [
            {
                "name": "Level 2: A",
                "weight": 2,
                "status" : 1,
                "parent": "Top Level",
                "children": [
                    {
                        "name": "Son of A",
                        "weight": 3,
                        "status" : 0,
                        "parent": "Level 2: A"
                    },
                    {
                        "name": "Daughter of A",
                        "weight": 4,
                        "status" : 0,
                        "parent": "Level 2: A"
                    }
                ]
            },
            {
                "name": "Level 2: B",
                "weight": 2,
                "status" : 1,
                "parent": "Top Level"
            }
        ]
    }
];

/************** Generate the tree diagram  *****************/
var margin = {top: 20, right: 120, bottom: 20, left: 120},
        width = 960 - margin.right - margin.left,
        height = 500 - margin.top - margin.bottom;

var i = 0;

var tree = d3.layout.tree()
        .size([height, width]);

var diagonal = d3.svg.diagonal()
        .projection(function(d) { return [d.y, d.x]; });

var body = d3.select("body");

var svg = body.append("svg")
        .attr("width", width + margin.right + margin.left)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var root = treeData[0];

var clickedNode;

update(root);

function update(source) {

    // compute the new tree layout.
    var nodes = tree.nodes(source).reverse(),
            links = tree.links(nodes);

    // normalize for fixed-depth.
    nodes.forEach(function(d) {
        d.y = d.depth * 180;
    });

    // declare the nodes
    var node = svg.selectAll("g.node")
            .data(nodes, function(d) { return d.id || (d.id = ++i); });

    // Enter the nodes.
    var nodeEnter = node.enter().append("g")
            .attr("class", "node")
            .attr("transform", function(d) {
                return "translate(" + d.y + "," + d.x + ")"; })
            .on("click", function(d) {
                var node = {
                    "name": "temp",
                    "weight": 2,
                    "status" : 1,
                    "parent": d
                };

                if(typeof d.children == "undefined") {
                    d.children = [node];
                } else {
                    d.children[d.children.length] = node;
                }

                update(d);

            });

    nodeEnter.append("circle")
            .attr("class", "nodeCir")
            .attr("r", 30)
            .style("fill", function(d) { return d.status ? "#83AF9B" : "#AF4933"; });

    nodeEnter.append("text")
            .attr("text-anchor", "middle")
            .html(function(d) { return d.name + "<br/>" + d.weight; });

    // Declare the links
    var link = svg.selectAll("path.link")
            .data(links, function(d) { return d.target.id; });

    // Enter the links.
    link.enter().insert("path", "g")
            .attr("class", "link")
            .attr("d", diagonal);

}

</script>

</body>
</html>


Заранее спасибо за помощь)
  • Вопрос задан
  • 3428 просмотров
Решения вопроса 1
@miroshnik Автор вопроса
android/java dev
Ответ нашелся здесь: bl.ocks.org/mbostock/999346
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы