Mike がここに投稿した回答では、インデックスまたはカスタム フィルターに基づいて、一致した要素に変更を適用する 3 つの異なる方法を概説しています。私は、できれば私自身だけでなく、より多くの人々のために、これらのソリューションの実際の選択を明確にしようとしています.
したがって、 class を持つ 6 つの SVG rect を持つドキュメントが与えられた.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
3 番目の四角形に a を適用したいとします。この四角形は次を使用して見つけることができます。
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 の優れたチュートリアルとドキュメントを読みましたが、理解できたと思ったとき、何かが浮かび上がってきて驚きました。では、これらの選択肢の違いは何ですか? また、どの選択肢をいつ使用すればよいかを知るにはどうすればよいでしょうか? ありがとうございます!長文失礼しました!