Javascript 在高级侦听器中获取对d3中事件目标的引用?

Javascript 在高级侦听器中获取对d3中事件目标的引用?,javascript,d3.js,svg,Javascript,D3.js,Svg,我使用d3在svg元素上创建了一个点击监听器: <svg height="100" width="100"> <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" id="a"> <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" id="b"> <cir

我使用d3在svg元素上创建了一个点击监听器:

<svg height="100" width="100">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" id="a">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" id="b">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" id="c">
</svg>
我想引用在处理程序中单击的圆圈(如果有)。然而,d3并没有给我一个事件的参考。我知道我可以在每个圆圈上放置一个侦听器,而不依赖于向
元素冒泡的事件,但我不想这样做,因为我计划以后动态添加更多圆圈,不想不得不小心地添加和删除侦听器。

要访问侦听器中的当前事件,请使用全局

这允许您访问与事件相关的所有内容,包括鼠标位置和事件源/目标(在
console.log()
中打印
d3.event

要获取ID,您可以:

d3.select('svg').on('click', function(d, i) {
    // Somehow console.log the ID of the circle clicked on (if any).
    console.log("Clicked ID: " + d3.event.target.id);
});

如果圆圈与示例中的位置相同,则事件将被您添加的最后一个圆圈捕获(除非您将其CSS属性更改为
none
),因为前面的圆圈将被隐藏。

您的圆圈是否真的相互堆叠?如果是,您只需单击最后一个圆圈(除非您使用“指针事件:在前一个事件上为“无”。)
d3.select('svg').on('click', function(d, i) {
    // Somehow console.log the ID of the circle clicked on (if any).
    console.log("Clicked ID: " + d3.event.target.id);
});