我正在尝试对 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>
最佳答案
最 D3 的方法是使用 filter
方法链接选择器:
var list1 = d3.selectAll(".mYc").filter(".101");
但这不起作用,因为类名不能以数字开头。所以你必须重命名为“a101”之类的东西,然后你就可以这样做
var list1 = d3.selectAll(".mYc").filter(".a101");
参见this fiddle .
关于svg - 如何将 D3 selectAll 与多个类名一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17435838/