D3.JS获取对被点击对象的绑定数据的引用

sma*_*ert 14 javascript d3.js force-layout

我是javascript和D3.js的新手

我正在使用https://gist.github.com/4062045上的Force Directed Graph Example

我需要获得对单击的圆元素的绑定数据的引用,以便我可以添加一个链接.

我在圈子的点击处理程序中有以下代码行:

d3.select(this).each(function(d){console.log(d)});
Run Code Online (Sandbox Code Playgroud)

我能够将对象打印到控制台,但我无法弄清楚如何获取对该对象的引用,以便我可以将其推送到链接对象,如:

{source: <reference to node should go here>, target: some_other_node}
Run Code Online (Sandbox Code Playgroud)

感谢你的帮助!

Wex*_*Wex 7

circles.on('click', datum => {
  console.log(datum); // the datum for the clicked circle
});
Run Code Online (Sandbox Code Playgroud)

# 选择.on(typenames [,listener [,capture ]])

在选定节点上调度指定事件时,将为每个选定元素计算指定的侦听器,传递当前数据(d),当前索引(i)和当前组(节点),并将其作为当前的DOM元素.


sma*_*ert 7

为了其他新手的利益,这就是我解决这个问题的方法:

//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); 
}
Run Code Online (Sandbox Code Playgroud)