Javascript D3 从元素获取属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43646573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
D3 get attributes from element
提问by Albin Vinoy
I am trying some basic d3 and i have been trying to get the attributes of each of the rectusing d3 but I am not able to get anything.
我正在尝试一些基本的 d3,我一直在尝试获取每个rect使用 d3的属性,但我什么也得不到。
When i try d3.selectAll("rect"), I get
当我尝试时d3.selectAll("rect"),我得到
How do can i access attributes of rectby using something like d3.selectAll("rect").select("part1").attr(...)or something similar? I want to access different attributes of all rect.
我如何rect使用类似d3.selectAll("rect").select("part1").attr(...)或类似的东西访问属性?我想访问所有rect.
回答by Gerardo Furtado
You can get any attribute of an element using a getter:
您可以使用getter获取元素的任何属性:
d3.select(foo).attr("bar")
Which is basically the attr()function with just one argument.
这基本上是attr()只有一个参数的函数。
Here is a demo. There are two classes of rectangles, part1and part2. I'm selecting all part1rectangles and getting their x positions:
这是一个演示。有两类矩形,part1和part2。我选择所有part1矩形并获取它们的 x 位置:
var svg = d3.select("svg");
var rects = svg.selectAll("foo")
.data(d3.range(14))
.enter()
.append("rect")
.attr("fill", "teal")
.attr("y", 20)
.attr("x", d => 10 + 12 * d)
.attr("height", 40)
.attr("width", 10)
.attr("class", d => d % 2 === 0 ? "part1" : "part2");
d3.selectAll(".part1").each(function(d,i) {
console.log("The x position of the rect #" + i + " is " + d3.select(this).attr("x"))
})
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>


