如何使用具有多个类名的D3 selectAll

Bil*_*oss 36 svg selectall d3.js

我正在尝试为SVG元素使用多个类名,以便(希望)我可以使用selectAll和类名的"部分"来选择它们的子集.不幸的是我没有尝试过任何工作,我没有在网上找到一个例子.下面的代码演示了我正在尝试用四个圆圈的简单示例.两个圆圈的类名称为"mYc 101",两个圆圈的类名为"mYc 202".selectAll(".mYc")给出所有四个圆圈.如果我只想要类名为"mYc 101"的圈子怎么办?可以这样做吗?怎么样?谢谢时间无限!!

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<div id="my_div"></div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
    var m_div = d3.select("#my_div");
    var m_svg = m_div.append("svg");

    var g = m_svg.append("g");

    g.append("circle")
        .attr("class", "mYc 101")
        .attr("cx", 100)
        .attr("cy", 100)
        .attr("r", 50) 
        .attr("style", "stroke: green; stroke-width: 8; fill: #000000");

    g.append("circle")
        .attr("class", "mYc 101")
        .attr("cx", 300)
        .attr("cy", 100)
        .attr("r", 50) 
        .attr("style", "stroke: green; stroke-width: 8; fill: #000000");

    g.append("circle")
        .attr("class", "mYc 202")
        .attr("cx", 100)
        .attr("cy", 300)
        .attr("r", 50) 
        .attr("style", "stroke: blue; stroke-width: 8; fill: #000000");

    g.append("circle")
        .attr("class", "mYc 202")
        .attr("cx", 300)
        .attr("cy", 300)
        .attr("r", 50) 
        .attr("style", "stroke: blue; stroke-width: 8; fill: #000000");

    // This selects all four circles
    var list = d3.selectAll(".mYc");

    // But if I want to select only class "mYc 101", none of these work.
    // In fact they all give an error.
    // var list1 = d3.selectAll(".mYc 101");
    // var list1 = d3.selectAll(".mYc .101");
    // var list1 = d3.selectAll(".mYc.101");
    // var list1 = d3.selectAll(".mYc,.101");
    // var list1 = d3.selectAll(".101");

</script>
</body>
Run Code Online (Sandbox Code Playgroud)

Lar*_*off 54

最常用的D3方法是使用以下filter方法链接选择器:

var list1 = d3.selectAll(".mYc").filter(".101");
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为类名不能以数字开头.所以你必须重命名为"a101",然后才能做到

var list1 = d3.selectAll(".mYc").filter(".a101");
Run Code Online (Sandbox Code Playgroud)

看到这个小提琴.


bob*_*et1 37

我发现这样做的另一种方法是同时选择两个类作为单个字符串,例如:

var list1 = d3.selectAll(".mYc.a101")
Run Code Online (Sandbox Code Playgroud)

如果你在中间添加一个空格,或者在它们之间添加一个逗号(它选择具有任何一个类的东西),它将不起作用.