gpt4 book ai didi

javascript - 使用 D3 将 SVG 文本元素 ID 与数据 ID 匹配

转载 作者:行者123 更新时间:2023-11-29 21:10:57 24 4
gpt4 key购买 nike

我有一堆 SVG 文本元素及其 id:

<text id = "id1">text1</text>
<text id = "id2">text2</text>
<text id = "id3">text3</text>
...
<text id = "abc1">textABC1</text>
<text id = "abc2">textABC2</text>
<text id = "abc3">textABC3</text>

以及来自 websocket 的数据:

var data = [{"id": "id1", "val":1}, {"id": "id2", "val":2}, {"id": "id3", "val":3}];

因此我需要更新文本元素中的文本(具有 val 属性),但仅适用于匹配 id = id* 的元素(不适用于 abc* id)

我尝试使用这个:

d3.selectAll("text")
.data(data, function(d) {
return this.id = d.id;
})
.text(function(d) {
return d.val;
});

但正如我所看到的,这里的逻辑是数据数组中的元素数量应该与选择中的元素数量相匹配

最佳答案

除非您提供键函数作为 selection.data([data[, key]]) 的第二个参数,否则数据将仅按索引匹配。 .

If a key function is not specified, then the first datum in data is assigned to the first selected element, the second datum to the second selected element, and so on. A key function may be specified to control which datum is assigned to which element, replacing the default join-by-index.

如果您确实提供了一个关键函数,但是,值得注意的是,该函数将首先为选择中的每个元素调用,然后将对数据中的每个新数据进行评估大批。或者,如文档所述:

This key function is evaluated for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodes[i]). The key function is then also evaluated for each new datum in data, being passed the current datum (d), the current index (i), and the group’s new data, with this as the group’s parent DOM element. The datum for a given key is assigned to the element with the matching key.

要通过 id 将您的新数据与现有文本匹配,您可以通过指定一个关键函数来使用它,如下所示:

d3.selectAll("text")
.data(data, function(d) { return this.id || d.id; })

这将在第一次运行中评估文本元素的 ID,即 this.id,并在第二次运行中评估数据 ID,从而将元素与新数据相匹配。

查看以下工作演示片段:

var data = [{"id": "id1", "val":1}, {"id": "id2", "val":2}, {"id": "id3", "val":3}];

d3.selectAll("text")
.data(data, function(d) { return this.id || d.id; })
.text(d => d.val);
<script src="https://d3js.org/d3.v4.js"></script>
<svg>
<text id="id1" y="10">text1</text>
<text id="id2" y="25">text2</text>
<text id="id3" y="40">text3</text>
<text id="abc1" y="55">textABC1</text>
<text id="abc2" y="70">textABC2</text>
<text id="abc3" y="85">textABC3</text>
</svg>

关于javascript - 使用 D3 将 SVG 文本元素 ID 与数据 ID 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41863966/

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