admin管理员组文章数量:1291814
I made a put a click listener on an svg element using d3:
<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).
});
I'd like to refer to the circle that was clicked on (if any) in the handler. However, d3 does not give me a reference to the event. I know that I could just put a listener on every circle and not rely on the event bubbling to the <svg>
element, but I don't want to do that since I plan to dynamically add more circles later and don't want to have to carefully add and remove listeners.
I made a put a click listener on an svg element using d3:
<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).
});
I'd like to refer to the circle that was clicked on (if any) in the handler. However, d3 does not give me a reference to the event. I know that I could just put a listener on every circle and not rely on the event bubbling to the <svg>
element, but I don't want to do that since I plan to dynamically add more circles later and don't want to have to carefully add and remove listeners.
- Are your circles really stacked on one another? If so, you are only going to click the last one (unless you used "pointer-events:none" on the previous ones.) – helderdarocha Commented Jul 11, 2016 at 0:18
1 Answer
Reset to default 8From the D3.js documentation:
"To access the current event within a listener, use the global d3.event.
This allows you to access everything related to the event, including mouse position and event source/target (print d3.event
in console.log()
).
To get the ID you could:
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);
});
If the circles are stacked in the same position as in your example, the event will be caught by the last circle you added (unless you change its pointer-events CSS property to none
), since the previous ones will be hidden.
本文标签: javascriptGet reference to target of event in d3 in highlevel listenerStack Overflow
版权声明:本文标题:javascript - Get reference to target of event in d3 in high-level listener? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741542019a2384376.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论