如何根据具有SelectAll的D3.js中的属性(填充颜色)选择元素

Isu*_*Isu 2 javascript css d3.js

我在地图上有一组圆圈,如10个红色圆圈,10个蓝色圆圈,10个绿色圆圈.如何使用d3 selectAll仅选择红色圆圈或选择?

或者还有其他方法吗?

颜色已经这样给出(作为"样式"属性中"填充"的值,

feature = g.selectAll("circle")
    .data(data)
    .enter().append("circle")
    .attr("id", function (d) {
    return d.ArtistID + d.FollowerID;
})
    .style("stroke", "black")
    .style("opacity", .6)
    .style("fill", function (d) {
    if (d.ArtistID == 1) {
        return "red"
    } else if (d.ArtistID == 2) {
        return "blue"
    } else {
        return "green"
    };
})
    .attr("r", 10);
Run Code Online (Sandbox Code Playgroud)

所以,圆圈会像这样绘制,

<circle id="10" r="10" transform="translate(695,236)" style="stroke: rgb(0, 0, 0); opacity: 0.6; fill: rgb(255, 255, 0);"></circle>
Run Code Online (Sandbox Code Playgroud)

我想选择红色的圆圈.Cam有人帮忙吗?

提前致谢.

mee*_*mit 5

您要求根据style属性的值进行选择.该fill属性嵌套在style属性中; 它不是DOM节点的直接属性.因此,您将无法使用属性选择器(即链接到@LarsKotthoff的方法)来选择它.

您可以使用SVG fill属性切换到设置填充, .attr('fill', ...)而不是使用style('fill'),这将允许您稍后使用属性选择器选择它.

除此之外,通过fill属性选择似乎并不太优雅.如果您的设计发展并且您开始使用不同的填充颜色,则还必须更改属性选择器.为它分配一个类并根据类选择更合适.

也许最好是根据数据进行选择.例如:

g.selectAll('circle')
  .filter(function(d) { return d.ArtistID == 1; })
  .style('fill', function(d, i) {
    // here you can affect just the red circles (bc their ArtistID is 1)
  })
Run Code Online (Sandbox Code Playgroud)