如何从JSON扩展子级,在单击父级后加载数据 - D3.Js - 强制定向布局

时间:2016-02-06 08:19:48

标签: javascript json d3.js

我想使用这个例子 http://bl.ocks.org/mbostock/1093130

链接为Collapsible Force Layout,并在首次加载时从JSON加载所有节点。

问题:

我想在点击父节点后加载子节点并在单击后展开。

当折叠每个节点时,销毁所有节点都是子节点。

如何实施创意?

注意:我的图表很大,网页浏览器不响应加载。现在我想逐渐加载/销毁数据。

1 个答案:

答案 0 :(得分:1)

你必须这样做:

单击该节点,获取与节点关联的子节点:

function getMyData(d) {
  //return the url for the parent node.
  if (d.name == 'graph') {
    return "https://gist.githubusercontent.com/cyrilcherian/231657f6c86d540adf64/raw/375f89aaa65d16bbbda904c7f17a132face1a7d6/graph_children.json";
  } else if (d.name == 'cluster') {
    return "https://gist.githubusercontent.com/cyrilcherian/dbf9f0b2180201e4cdbe/raw/a7e6361349fe06b6c16f7f376d07dae36da89848/cluster_children.json";
  }  else if (d.name == 'analytics') {
    return "https://gist.githubusercontent.com/cyrilcherian/0efc76bd75386bf89961/raw/5d32ea77f1d34e8ca40f749ce9d501669e8563a4/analytic_children.json";
  } else if (d.name == 'flare') {
    return "https://gist.githubusercontent.com/cyrilcherian/b9bcb0fdc398bd691641/raw/11a79edf99511cf040ffcb98ae9c30895798ae5e/flare.json";
  } else
    return [];
}

// Toggle children on click.
function click(d) {

  if (d3.event.defaultPrevented) return; // ignore drag
  if (d.children) {
    d.children = null;
    update();
  } else {
    //do your ajax call to get the chldren

    var url = getMyData(d);
    d3.json(url, function(error, json) {
      d.children = json;
      update();//update on ajax success.
    })

  }

}

这些是我根据父节点"https://gist.githubusercontent.com/cyrilcherian/b9bcb0fdc398bd691641/raw/11a79edf99511cf040ffcb98ae9c30895798ae5e/flare.json"

加载子节点的ajax调用

工作代码here

您需要点击flare / cluster / graph / analytics节点以通过ajax加载其子节点。

希望这有帮助!