簡體   English   中英

d3js:創建可折疊的表和嵌套數據問題

[英]d3js: Creating a collapsible table & issues with nested data

我正在d3js中創建可折疊表,但是正在使用的數據結構的嵌套性質存在問題。 數據的組織方式如下:

var source = [
{name: William, age: 40, children: [{name: Billy, age: 10},{name:Charles, age: 12}]},
{name: Nancy, age: 35, children: [{name: Sally, age:8}]}
]

當我第一次創建表時,將children數組移到每個父對象中的_children對象中,如下所示:

tableData.forEach(function(d) {
  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }
});

使用d3js的典型數據輸入,我可以為表中的每個父級填充一行和坐標。

source.forEach(function(d) {
    d.x = x0;
    d.y = y0;
    var parentX = x0,
      parentY = y0;
    y0 += barHeight + padding;
    if (d.children) {
      d.children.forEach(function(data) {
        data.x = x0;
        data.y = y0;
        data.parentX = parentX;
        data.parentY = parentY;
        y0 += barHeight + padding;
        shownChildren.push(data);
      })
    }
  });

我利用通常的數據選擇方法:

var tableRow = tableSvg.selectAll('.tableRow')
  .data(source);

var rowEnter = tableRow.enter()
  .append("g")
  .classed("tableRow", true)
  .attr("transform", function(d) {
    return "translate(" + d.x + "," + d.y + ")"
  });

放置代表每一行的矩形:

var rowRect = rowEnter.append("rect")
  .attr("height", barHeight)
  .attr("width", barWidth)
  .style("fill", color)
  .on("click", click);

var rowText = rowEnter.append("text")
  .attr("dy", 15)
  .attr("dx", 5.5)
  .text(function(d) {
    if (d.name.length > 70) {
      return d.name.substring(0, 67) + "...";
    } else {
      return d.name;
    }
  })
  .on("click", click);

單擊一行后,這些行將移動以為額外的子行騰出空間,並將和_children數組移回children ,上面的代碼為每個子級分配一個位置,然后在其中顯示它們:

function click(d) {
  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }
  updateTable(source);
}

但是,當我使用與上述父母完全相同的方式為每個孩子創建行時,就會出現問題。 我當前的實現構建一個數組shownChildren (如第三個代碼塊所示),並在表中填充子項。 最初,該實現似乎運行良好,但是當您單擊行時,每個子行都會更改位置。

我對目前導致問題的原因沒有任何猜測。

這是我在jsfiddle上擁有的代碼的摘要

我遇到的問題是,每次使用不同數量的孩子時,我都在重建shownChildren數組。 我加入所有的固定的問題, children_childrenshownChildren陣列(總是以相同的順序!)和隱藏每個的_children各自在父母后面。

更新了jsfiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM