2012-07-19 71 views
7

所以我試圖使自己的這華麗的可視化版本的D3做:如何訪問SVG元素一個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 

源對象內,(這是我試圖訪問)有一個名爲關鍵領域,這就是我想要訪問

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名在同一時間,即使我用全選。

任何幫助將不勝感激!如果問題有點複雜,我很抱歉,我試圖儘可能具體,因爲這是一個非常具體的問題,但我可能會詳細說明......如果可能的話。無論如何,先謝謝了!

sourcetarget變量艾薩克

回答

3

使用each讓每一個值,他們返回,而不只是第一個值。

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

+0

這很有道理,但是當我嘗試這樣做時,控制檯顯示:Uncaught TypeError:Object# has no method'property' – Cabbibo 2012-07-19 18:57:11

+1

嘗試'imports.push(d [「target」] .key);'改爲。如果這不起作用,請嘗試添加'console.log(d)'來查看'd'具有的字段。 – 2012-07-19 19:29:37

+0

我很抱歉,但我不明白如何imports.push(D [「目標」]。鍵);是不同的,那麼代碼已經是什麼了?此外,d是一個包含導入的對象,但我需要更多的導入和導出,這是此問題的最大來源。 – Cabbibo 2012-07-19 21:00:58