我正在尝试对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>发布于 2013-07-03 05:26:46
要做到这一点,最D3的方法是使用filter方法链接选择器:
var list1 = d3.selectAll(".mYc").filter(".101");这是行不通的,因为类名不能以数字开头。因此您必须重命名为类似于"a101“的名称,然后您可以这样做
var list1 = d3.selectAll(".mYc").filter(".a101");参见this fiddle。
发布于 2014-05-04 08:24:33
我发现的另一种方法是同时选择两个类作为单个字符串,例如:
var list1 = d3.selectAll(".mYc.a101")如果你在中间加一个空格,或者在中间加一个逗号(这会选择任何一个类的东西),它就不会起作用。
https://stackoverflow.com/questions/17435838
复制相似问题