7

所以我正在尝试制作我自己的 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;

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

console.log(imports)

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

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

艾萨克

4

1 回答 1

3

使用and变量来获取它们返回的每个值,而不仅仅是第一个值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方法喜欢attr和在幕后style使用each,所以您不必这样做,但由于您使用自定义函数来访问数据,您将需要使用each.

于 2012-07-19T18:39:38.560 回答