在 Mike 发布的答案中 here ,他概述了三种不同的方法来根据索引或自定义过滤器将更改应用于匹配元素。我试图澄清这些解决方案中的实际选择,希望不仅仅是我自己。
给定一个包含 6 个 SVG 矩形的文档,类为 .bar
,我们有这些不同的选择以及它们返回的内容:
d3.select(".bar"):
[Array[1]
0: rect.[object SVGAnimatedString]
length: 1
parentNode: html
__proto__: Array[0]
d3.selectAll(".bar"):
[Array[6]
0: rect.[object SVGAnimatedString]
1: rect.[object SVGAnimatedString]
2: rect.[object SVGAnimatedString]
3: rect.[object SVGAnimatedString]
4: rect.[object SVGAnimatedString]
5: rect.[object SVGAnimatedString]
length: 6
parentNode: html
__proto__: Array[0]
$(".bar"):
[
<rect class="dataBars" x="53.191489361702125" width="212.7659574468085" y="4.761904761904762" height="11.11111111111111"></rect>,
<rect class="dataBars" x="74.46808510638297" width="372.3404255319149" y="20.634920634920636" height="11.11111111111111"></rect>,
<rect class="dataBars" x="127.6595744680851" width="212.7659574468085" y="36.507936507936506" height="11.11111111111111"></rect>,
<rect class="dataBars" x="31.914893617021274" width="212.7659574468085" y="52.38095238095238" height="11.11111111111111"></rect>,
<rect class="dataBars" x="159.5744680851064" width="265.9574468085106" y="68.25396825396825" height="11.11111111111111"></rect>,
<rect class="dataBars" x="234.04255319148936" width="138.29787234042553" y="84.12698412698413" height="11.11111111111111"></rect>,
]
现在这是更棘手的地方(至少对我而言),假设我想将 style
应用于第三个矩形,可以使用
d3.selectAll(".bar")[0][2]
但是如果我们想使用 d3.selection.attr()
,它会返回
TypeError: Property 'style' of object #<SVGRectElement> is not a function
但是我们可以包装这个选择
d3.select(d3.selectAll(".bars rect")[0][2]).style("fill", "red")
这将按预期工作。
然后,如果我们要应用过滤器,例如
filter(function (d) { return d === 5 || d === 15;}
必须使用 d3.selectAll(".bar")
,d3.select(d3.selectAll(".bar"))
将无法正常工作.
我已经阅读了 Mike 关于选择的优秀教程和文档,但就在我认为自己明白了的时候,突然出现了一些让我吃惊的东西。那么这些选择之间有什么区别,我如何知道何时使用哪一个?非常感谢,很抱歉发了这么长的帖子!
最佳答案
我过去曾尝试这样做并遇到过类似的错误。然后我意识到我并没有真正遵循预期的 API。一旦您开始按索引访问选择元素,您就大错特错了。
所以,如果你想设计你的第三个栏,你会这样做
d3.selectAll(".bar").style("color", function(d,i) { return i === 2 ? "red" : null; } )
如果您选择的嵌套比那多一层,请将其设为 function(d,i,j)
并从那里开始。等等
关于javascript - D3 中的选择,Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17818045/