将动态属性名称添加到选择中

Adding a dynamic attribute name to a selection

本文关键字:选择 添加 动态 属性      更新时间:2023-09-26

我有这个:

g.append(function(d) {
  return document.createElementNS("http://www.w3.org/2000/svg", d.shape);
})

其中,d.shape可以是circlepolygon。现在,根据形状,我想添加一个属性。对于圆形:

.attr('r', 12)

对于多边形:

.attr('points', '05,30 15,10 25,30'))

但是我不知道如何添加这个变量对属性名称/值。有可能吗?这里有一个相关的jsbin。

我会为此使用一个选择过滤器,过滤元素的nodeName属性:

d3.selectAll("top_level_selector") //or use existing selection from appending
.filter(function(d,i){
    return this.nodeName == 'circle';
})
.attr("r", 12);

-https://github.com/mbostock/d3/wiki/Selections#wiki-过滤

或者可能只是在属性函数内部检查正确的节点类型:

selection
.attr('r',function(d,i){
    if(this.nodeName =='circle'){ return 12 }
});

我不是肯定的,但我认为当它试图将未定义的"r"属性分配给非圆元素时(对于圆上的"点"等等),这不会带来问题。