简体   繁体   English

D3在svg对象中选择多个元素

[英]D3 selecting multiple elements in an svg object

I've got a bar chart and I'm putting in some labels (after already having created the bars) like this: 我有一个条形图,并且正在像这样创建一些条形图(在已经创建了条形图之后):

svg.selectAll("text").data(labels).enter().append("text").text(function(d) { return d; })
.attr("text-anchor", "middle")
.attr("x", parseFloat(d3.selectAll("#bar").attr("x")) + 
           parseFloat(d3.selectAll("#bar").attr("width"))/2)
.attr("y", 90);

};
//when I am creating the bars using selectAll("rect").... at the end of the attr()
//function I have specified an id called bar so I can reference it later that way.

But this only selects the first bar and puts all labels on top of each other. 但这只会选择第一个条,并将所有标签都放在另一个顶部。 Why is that and how can I select all the rectangles in the svg? 为什么会这样,如何选择svg中的所有矩形?

#bar is an id selector and every id must be unique within a document or your file isn't valid. #bar是一个ID选择器 ,每个ID在文档中必须唯一,否则文件无效。

If you want to have multiple elements called bar you could give them a class of bar and then use a class selector instead. 如果要有多个称为bar的元素,则可以给它们提供bar类,然后使用类选择器代替。

If you want to select all <rect> elements then you could use a type selector . 如果要选择所有<rect>元素,则可以使用类型选择器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM