gpt4 book ai didi

d3.js - 如何合并或加入来自不同 d3.selects 的 d3 选择?

转载 作者:行者123 更新时间:2023-12-04 08:09:12 26 4
gpt4 key购买 nike

在我的代码中,我在合并选择时遇到了问题。精简代码如下。

<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<svg>
<g id="g1" class="testg"><text x="20" y="20">bla1</text></g>
</svg>
<svg>
<g id="g2" class="testg"><text x="20" y="20">bla2</text></g>
</svg>

<script>
let s0 = d3.selectAll("g");
s0.style("fill", "red"); // works, all are red;

let s1 = d3.select("g#g1");
let s2 = d3.select("g#g2");

s1.style("fill", "green"); //works g1 green
s2.style("fill", "yellow"); //works g2 yellow

let s3 = s1.merge(s2);
s3.style("fill", "pink"); // does not work: only g1 is pink
</script>
</body>
</html>
我希望这能奏效,但事实并非如此。如何将 s1 和 s2 合并为一个选择?在我的实时代码中,它们不容易通过属性进行选择。
编辑:
当然,我可以解决这样的问题:
  s1.classed("select_for_merge", true);
s2.classed("select_for_merge", true);
s3 = d3.selectAll("g.select_for_merge");
s3.classed("select_for_merge", false);
考虑到我已经有多个选择,仅来自应用程序的不同部分,这似乎很笨拙。为它们提供所有额外的类是笨拙的并且会妨碍性能,在实时代码中它由 4 个维度的许多元素组成。

最佳答案

您目睹的行为是意料之中的,而且很好documented :

# selection.merge(other) · Source

This method is not intended for concatenating arbitrary selections, however: if both this selection and the specified other selection have (non-null) elements at the same index, this selection’s element is returned in the merge and the other selection’s element is ignored.


这就解释了为什么只有 #g1合并操作后选择元素。
虽然有多种方法可以做到这一点,但我更喜欢,也许是最优雅的方法,是通过 release 实现的。 D3 v6。选择现在实现了一个迭代器,因此它们本身是可迭代的,这使得它们可以被 ES6 引入的许多语言功能访问!通常,使用 spread syntax 可以轻松实现连接数组。 :
const concatArray = [...array1, array2];
由于选择现在是可迭代的,您可以以相同的方式连接它们各自的节点:
const concatNodes = [...selection1, ...selection2];
除了可迭代之外,还可以通过传入可迭代对象来创建选择,这会产生以下用于合并两个选择的代码:
const mergedSelection = d3.selectAll([...selection1, ...selection2]);
鉴于您的示例,这可以按如下方式实现:

const s0 = d3.selectAll("g");
s0.style("fill", "red"); // works, all are red;

const s1 = d3.select("g#g1");
const s2 = d3.select("g#g2");

const s3 = d3.selectAll([...s1, ...s2]);
s3.style("fill", "blue"); // works, all are blue
<script src="https://d3js.org/d3.v6.js"></script>
<svg>
<g id="g1" class="testg"><text x="20" y="20">bla1</text></g>
</svg>
<svg>
<g id="g2" class="testg"><text x="20" y="20">bla2</text></g>
</svg>

关于d3.js - 如何合并或加入来自不同 d3.selects 的 d3 选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66065895/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com