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

Joh*_*man 4 javascript svg d3.js

我使用 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>
Run Code Online (Sandbox Code Playgroud)

Javascript:

d3.select('svg').on('click', function(d, i) {
  // Somehow console.log the ID of the circle clicked on (if any).
});
Run Code Online (Sandbox Code Playgroud)

我想引用处理程序中点击的圆圈(如果有的话)。但是, d3 没有给我一个事件的参考。我知道我可以在每个圆圈上放置一个监听器,而不是依赖于事件冒泡到<svg>元素,但我不想这样做,因为我计划稍后动态添加更多圆圈并且不想仔细添加和删​​除侦听器。

hel*_*cha 8

D3.js 文档

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

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

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

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