2013-02-09 52 views
12

我是一個新手,javascript和D3.jsD3.JS得到參考點擊對象的綁定數據

我在https://gist.github.com/4062045

與部隊向圖實例工作,我需要去參考點擊的圓形元素的綁定數據,以便我可以添加鏈接到它。

我的代碼在圈內的單擊處理以下行:

d3.select(this).each(function(d){console.log(d)}); 

我能夠打印對象安慰,但我無法弄清楚如何獲得引用此對象,我可以將它推入鏈接對象,如:

{source: <reference to node should go here>, target: some_other_node} 

感謝您的幫助傢伙!

回答

5
circles.on('click', datum => { 
    console.log(datum); // the datum for the clicked circle 
}); 

#選擇typenames [,聽者 [,捕獲]])

當指定事件被選擇的節點上調度,指定偵聽將每個選定元件評價,被傳遞當前數據(d),當前索引(i)和當前組(節點),並將其作爲當前DOM元素。

+0

感謝您指點我在正確的方向Wex。您的評論讓我意識到我只需要從selection.on獲取綁定數據的引用,而不是嘗試使用「this」從事件處理函數中獲取引用。 – smartexpert 2013-02-09 09:00:31

+0

這是一條評論,而不是一個答案..我正在尋求相同的信息,這個答案沒有幫助,只是指向鏈接 – vsync 2016-10-05 10:20:40

+0

@vsync做編輯我的答案幫助? – Wex 2016-10-06 14:52:22

6

對於其他新手在那裏的利益,這是我如何解決了這個:

//Register the event handler with you selection 
myselection.on("click", click); 

//Obtain reference to data of currently clicked element by obtaining the first argument of  the event handler function 

function click(element){ 
    console.log(element); 
} 
+1

請注意,第一個參數是* datum *而不是* element *。 *這個*是DOM元素。 – Wex 2016-10-07 13:25:25

-1

這裏是我的解決方案:

/* CSS used in Javascript snippet */ 
.source { 
    stroke-width: 3px !important; 
    stroke-opacity: 1; 
    stroke: #0f0; 
} 

.target { 
    stroke-width: 3px !important; 
    stroke-opacity: 1; 
    stroke: #f00; 
} 


// this goes inside the d3.json call 
node.on("mouseover", function() { 
    idx = this.__data__.index 
    for (i = 0; i < graph.links.length; i++) { 
    if (graph.links[i].source.index == idx) { 
     link[0][i].classList.add("source"); 
    } 
    else if (graph.links[i].target.index == idx) { 
     link[0][i].classList.add("target"); 
    } 
    else { 
     link[0][i].classList.remove("source"); 
     link[0][i].classList.remove("target"); 
    } 
    } 
}); 

的想法是,對一個在trigering給定的事件,您將查看鏈接列表,並向其源或目標與給定節點數據中找到的索引相匹配的每個鏈接突出顯示(添加一個類)。它可能並沒有完成d3所能做的所有事情,但它不需要額外的庫,而且我正在快速突出顯示我的源/目標鏈接。