如何访问d3 SVG元素的数据

时间:2012-07-19 18:17:37

标签: dom svg element visualization d3.js

所以我正在尝试制作我自己的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(),但我似乎一次只能访问一个元素,我正在使用的是

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)
即使我使用了selectAll,

也会一次只给我1个名字。

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

艾萨克

1 个答案:

答案 0 :(得分:3)

eachsource变量上使用target获取他们返回的每个值,而不仅仅是第一个值。

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函数中,因为这是突出显示的地方。

D3attrstyle等方法在幕后使用each,因此您不必这样做,但由于您使用的是自定义函数来访问数据需要使用each