gpt4 book ai didi

javascript - D3JS V4 根据值停止追加 tspan

转载 作者:太空宇宙 更新时间:2023-11-04 15:36:45 27 4
gpt4 key购买 nike

我有一些创建树状图的 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 size = 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com