我有一些D3.js代码可创建树形图,但是我尝试对代码进行一些更改以阻止为值0的元素打印不必要的标签。

以下代码似乎添加了tspan并为其提供了文本值。但是,如果从.text(function(d){});内部似乎无法访问的d.data.size值为0,我不希望显示标签!

有什么建议么?

更新
数据结构如下:

{"name":"Gradings","children":[{"name":"Full Assurance","children":[{"name":"Domains","children":[{"name":"D1","size":8},{"name":"D2","size":7},{"name":"D3","size":11},{"name":"D4","size":8},{"name":"D5","size":2},{"name":"D6","size":3},{"name":"D7","size":3},{"name":"D8","size":4}]}]},{"name":"Substantial Assurance","children":[{"name":"Domains","children":[{"name":"D1","size":7},{"name":"D2","size":3},{"name":"D3","size":5},{"name":"D4","size":2},{"name":"D5","size":2},{"name":"D6","size":2},{"name":"D7","size":1},{"name":"D8","size":4}]}]},{"name":"No Assurance","children":[{"name":"Domains","children":[{"name":"D1","size":5},{"name":"D2","size":1},{"name":"D3","size":3},{"name":"D4","size":2},{"name":"D5","size":0},{"name":"D6","size":1},{"name":"D7","size":1},{"name":"D8","size":2}]}]},{"name":"Limited Assurance","children":[{"name":"Domains","children":[{"name":"D1","size":4},{"name":"D2","size":1},{"name":"D3","size":2},{"name":"D4","size":1},{"name":"D5","size":0},{"name":"D6","size":0},{"name":"D7","size":1},{"name":"D8","size":1}]}]}]}


我认为需要更改的代码是:

cell.append("text")
        .attr("clip-path", function (d)
        {
            return "url(#clip-" + d.data.id + ")";
        })
        .selectAll("tspan")
        .data(function (d)
        {
            return d.data.name.split(/(?=[A-Z][^A-Z])/g);
        })
        .enter().append("tspan")
        .style('fill', 'black')
        .style('font-weight', 'bold')
        .attr("x", 4)
        .attr("y", function (d, i)
        {
            return 13 + i * 10;
        })
        .text(function (d)
        {
            return d;
        });

最佳答案

在您的输入选择中,您可以通过以下方式获取父选择的数据:

d3.select(this.parentNode).data();


因此,在您的text函数中,您可以编写如下内容:

.text(function(d) {
    if (d3.select(this.parentNode).data()[0].size !== 0) {
        return d;
    }
})


或使用三元运算符也一样。

这是一个使用(部分)数据的演示。我更改了数据,使D4的大小=0。将打印所有名称,除了D4



var data = [{
  "name": "D1",
  "size": 8
}, {
  "name": "D2",
  "size": 7
}, {
  "name": "D3",
  "size": 11
}, {
  "name": "D4",
  "size": 0
}, {
  "name": "D5",
  "size": 2
}, {
  "name": "D6",
  "size": 3
}, {
  "name": "D7",
  "size": 3
}, {
  "name": "D8",
  "size": 4
}];

var svg = d3.select("svg");
var texts = svg.selectAll(null)
  .data(data)
  .enter()
  .append("text")
  .attr("x", 20)
  .attr("y", function(d, i) {
    return 20 + 16 * i
  })
  .selectAll(null)
  .data(function(d) {
    return d.name
  })
  .enter()
  .append("tspan")
  .text(function(d) {
    if (d3.select(this.parentNode).data()[0].size !== 0) {
      return d;
    }
  })

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

关于javascript - D3JS V4根据值停止追加tspan,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44284984/

10-09 17:49