简体   繁体   English

在d3树形图中获取父节点到给定节点

[英]get the parent nodes to a given node in d3 dendogram

I am a beginner in javascript/flask and I am trying to experiment with this d3 dendogram example: https://bl.ocks.org/mbostock/4063570 我是javascript / flask的初学者,我正在尝试使用这个d3树形图示例: https ://bl.ocks.org/mbostock/4063570

What I am trying to get is, when a node is clicked, return the parent nodes to the flask app server. 我想要的是,当点击一个节点时,将父节点返回到烧瓶应用服务器。

For example: If i click on display node, then server gets " flare,display " 例如:如果我点击display节点,那么服务器将获得“ flare,display

if cluster node is clicked, then server gets " flare,analytics,cluster " 如果单击cluster节点,则服务器将获得“ flare,analytics,cluster

It's very simple to get the parents of the clicked node. 获取被点击节点的父母非常简单。 Just use ancestors() , which: 只需使用ancestors() ,其中:

Returns the array of ancestors nodes, starting with this node, then followed by each parent up to the root. 返回祖先节点的数组,从此节点开始,然后是每个父节点,直到根节点。

So, in your case... 所以,在你的情况下......

node.on("click", function(d){
    console.log(d.ancestors())
});

.. will show all the ancestors in the console, as an array. ..将显示控制台中的所有祖先,作为一个数组。

Here is the forked bl.ocks: https://bl.ocks.org/anonymous/e36d4af364642a70818987941aa192c8/c75e620e662a6899d8df34c287fc5ea00d049513 这是分叉的bl.ocks: https ://bl.ocks.org/anonymous/e36d4af364642a70818987941aa192c8/c75e620e662a6899d8df34c287fc5ea00d049513

In that code I'm mapping the array to get the id property of each node. 在该代码中,我将映射数组以获取每个节点的id属性。

You can recurse over the clicked data: 您可以对点击的数据进行递归:

var node = g.selectAll(".node")
      .data(root.descendants())
    .enter().append("g")
      .attr("class", function(d) { return "node" + (d.children ? " node--internal" : " node--leaf"); })
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
      //attach a click listener to the group
      .on("click", function(d){
        var children = [];
        //recursively call parent
        var recurse = function(c){
          //recurse unless no parent is found
          if (c.parent){
            children.push(c.parent.id);
            recurse(c.parent)
          }
        }
        recurse(d)//call recurse on clicked node
        console.log(children)
        //send children to server via AJAX
      })

working example here 这里的工作范例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM