简体   繁体   English

如何从d3节点数据中获取dom svg元素?

[英]How can I get the dom svg element from d3 node data?

I have nodes variable that is an array with all nodes from graph. 我有nodes变量,它是一个包含图中所有节点的数组。 Each node has a SVG g (group) SVG element in DOM. 每个节点在DOM中都有一个SVG g (组)SVG元素。

To select the data having the DOM element I do d3.select(myElement).data()[0] , but how can I get the DOM element having the data? 要选择具有DOM元素的数据,我执行d3.select(myElement).data()[0] ,但是如何获取具有数据的DOM元素?

You can do this using D3's data matching. 您可以使用D3的数据匹配来完成此操作。 The idea is to have the data "identify" the correct element for you. 我们的想法是让数据为您“识别”正确的元素。

d3.selectAll("allMyElements").data([datumIwantElementFor], suitableKeyFunction);

Complete demo here . 在这里完成演示。

To be clear, I do not recommend taking this approach. 需要说明的是,我建议采用这种方法。 This is prone to breaking when you add more elements to the document and accidentally select some of those, use the same data in more than one place, or change the data format. 当您向文档添加更多元素并意外选择其中一些元素,在多个位置使用相同数据或更改数据格式时,这很容易破坏。 It will lead to bugs that are really hard to spot unless you know what you're looking for. 它会导致很难发现的错误,除非你知道你在寻找什么。

A better approach is to assign an ID or class from that data to each element that you bind the data to so that you can select it directly when you have the data. 更好的方法是将数据中的ID或类分配给绑定数据的每个元素,以便在获得数据时可以直接选择它。 This will also be more efficient. 这也会更有效率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM