[英]Get reference to target of event in d3 in high-level listener?
我使用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>
使用Javascript:
d3.select('svg').on('click', function(d, i) {
// Somehow console.log the ID of the circle clicked on (if any).
});
我想引用处理程序中单击的圆圈(如果有的话)。 但是,d3没有给我参考这个事件。 我知道我可以在每个圈子上放置一个监听器,而不是依赖于冒泡到<svg>
元素的事件,但我不想这样做,因为我打算以后动态添加更多的圈子而不想必须仔细添加和删除听众。
从D3.js文档 :
“要在侦听器中访问当前事件,请使用全局d3.event 。
这允许您访问与事件相关的所有内容,包括鼠标位置和事件源/目标(在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
),因为之前的圆圈将被隐藏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.