我正在尝试使用 D3 中的力布局构建一个图形。我想根据数据构建不同外观的节点。目前所有节点都有一个类别和一个名称。所以我画了一个 svg:g
,它由两个 rect
和两个 text
元素组成。
我的代码目前看起来像这样:
// nodes are in the form: { group: 'string', name: 'string2' }
this.node = this.node.data(this.node, function(d) { return d.id; });
var g = this.node.enter().
append('svg:g').
attr('transform', function(d) { return 'translate('+ d.x +','+ d.y +')'; });
g.append('svg:rect').attr('h', 20).attr('w', 100);
g.append('svg:rect').attr('y', 20).attr('h', 20).attr('w', 100);
g.append('svg:text').text(function(d) { d.group; });
g.append('svg:text').attr('y', 20).text(function(d) { d.name; });
但是,如果节点没有名称,我想禁止创建第二个 rect
和 text
。从逻辑上讲,如果不是 d3 中的隐式迭代器,我会做类似的事情:
var g = this.node.enter().
append('svg:g').
attr('transform', function(d) { return 'translate('+ d.x +','+ d.y +')'; });
g.append('svg:rect').attr('h', 20).attr('w', 100);
g.append('svg:text').text(function(d) { d.group; });
// unfortunately 'd' isn't defined out here.
// EDIT: based on comment from the answer below; the conditional should
// be for the text and the related rectangle.
if(d.name) {
g.append('svg:rect').attr('y', 20).attr('h', 20).attr('w', 100);
g.append('svg:text').attr('y', 20).text(function(d) { d.name; });
}
最佳答案
您可以对 g
选择使用 each
调用来决定是否添加标签。
g.each(function(d) {
if (d.name){
var thisGroup = d3.select(this);
thisGroup.append("text")
.text(d.group);
thisGroup.append("text")
.attr("y", 20)
.text(d.name);
});
但是,请注意,如果您要更新数据,此结构可能会造成混淆。
如果你希望能够整齐地更新,我建议做一个嵌套选择:
var labels = g.selectAll("text")
.data(function(d){ d.name? [d.group, d.name]:[]; });
labels.enter().append("text");
labels.exit().remove();
labels.text(function(d){return d;})
.attr("y", function(d,i){return i*20;});
data-join 函数测试父级的数据对象,并基于它传递一个数组,其中包含您要用于标签文本的两个值,或者传递一个空数组。如果它传递空数组,则不会创建任何标签;否则,每个标签的文本由数组中的值设置,垂直位置由索引设置。
关于javascript - 在 d3 中有条件地构建组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21788902/