gpt4 book ai didi

dom - 如何访问 d3 SVG 元素的数据

转载 作者:行者123 更新时间:2023-12-04 12:42:20 36 4
gpt4 key购买 nike

因此,我正在尝试为 d3 所做的这个华丽的可视化制作我自己的版本:

http://mbostock.github.com/d3/talk/20111116/bundle.html

我所做的基本上就是将整个图表向左移动,然后尝试在右侧显示不同的关系,因此每次将鼠标悬停在左侧的名称上时,不仅会看到不同类型的连接在在图表中,您还会在右侧看到这些连接的名称。

我遇到的问题是访问连接的实际名称。我是 javascript 新手,甚至是 d3 的新手,并且在理解如何访问这些 SVG 元素的实际名称时遇到问题到目前为止,我只是在 console.log() 中使用两行代码进行操作:

var targetTest = d3.selectAll("path.link.target-" + d.key);
console.log(targetTest);

在控制台中,这将为我提供我想要的所有 SVG 对象的日志,但它为我提供了每个元素的完整信息。像这样的东西:
0: SVGPathElement
__data__: Object
animatedNormalizedPathSegList: null
animatedPathSegList: SVGPathSegList
attributes: NamedNodeMap
baseURI: "http://localhost/mbostock-d3- 544addb/examples/bundle2/bundle.html"
childElementCount: 0
childNodes: NodeList[0]
className: SVGAnimatedString
clientHeight: 0
clientLeft: 0
clientTop: 0
clientWidth: 0
dataset: DOMStringMap
externalResourcesRequired: SVGAnimatedBoolean
farthestViewportElement: SVGSVGElement
firstChild: null
firstElementChild: null
id: ""
lastChild: null
lastElementChild: null
localName: "path"
namespaceURI: "http://www.w3.org/2000/svg"
nearestViewportElement: SVGSVGElement
nextElementSibling: SVGPathElement
nextSibling: SVGPathElement
nodeName: "path"
nodeType: 1
nodeValue: null
normalizedPathSegList: null
offsetHeight: 0
__proto__: SVGPathElement
length: 1
parentNode: HTMLDocument
__proto__: Array[0]

我试图访问的数据部分在 内数据对象,其中包含另外三个对象。
source: Object
target: Object
__proto__: Object

在源对象中,(这是我试图访问的)有一个名为 key 的字段,这是我想要访问的字段
depth: 4
imports: Array[9]
key: "Interpolator"
name: "flare.animate.interpolate.Interpolator"
parent: Object
size: 8746
x: 40.62256809338521
y: 180

基本上我想在这个键上调用一个 document.write 或类似的 $(#id).text() ,但我似乎一次只能访问一个元素,AKA 我正在使用
var target = d3.selectAll("path.link.target-" + d.key);
var source = d3.selectAll("path.link.source-" + d.key);
var imports = source.property("__data__").target.key;
var exports = target.property("__data__").source.key;

但每一个都只会给我一个名字,而不是一个完整的列表。
也就是当我将鼠标悬停在一个元素上时,即使它有多个“导入”或“导出”
console.log(imports)

一次只会给我 1 个名字,即使我使用了 selectAll。

任何帮助将非常感激!如果问题有点复杂,我很抱歉,我试图尽可能具体,因为这是一个非常具体的问题,但我可能已经详细说明了......如果可能的话。无论如何,先谢谢!

以撒

最佳答案

使用 eachsourcetarget变量来获取它们返回的每个值,而不仅仅是第一个值。

var targets = d3.selectAll("path.link.target-" + d.key);
var sources = d3.selectAll("path.link.source-" + d.key);
var imports = [];
var exports = [];
targets.each(function(d) {
imports.push(d["source"].key);
});
sources.each(function(d) {
exports.push(d["target"].key);
});
console.log("Imports - " + imports);
console.log("Exports - " + exports);

这是一个 JSFiddle在行动中展示它。我将上面的代码添加到 mouseover功能,因为这是突出显示的地方。
D3方法如 attrstyle使用 each在幕后,因此您不必这样做,但由于您使用自定义函数来访问数据,因此您需要使用 each .

关于dom - 如何访问 d3 SVG 元素的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11566935/

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