[英]Firing D3 event for an element
I have attached a click
event to an element of a D3 chart:我已将click
事件附加到 D3 图表的元素:
import * as d3 from 'd3';
const vis = {}
vis.svg = d3.select(element)
.append("svg")
.attr("width", 500)
.attr("height", 500)
vis.g = vis.svg
.append("g")
const circles = [20];
const myCircles = vis.g.selectAll('circle').data(circles).enter()
myCircles
.append('circle')
.attr('id', (d, i) => { return 'myCircle' + i})
.attr('cx', 100)
.attr('cy', 100)
.attr('r', (d, i) => d)
.attr('fill', 'gainsboro')
.attr('stroke', 'grey')
.on('click', function(event, d) {
d3.select(this).attr('stroke', 'black')
d3.select(this).attr('stroke-width', '2px')
})
Is there a way to fire this click
event from outside of an element?有没有办法从元素外部触发这个click
事件? I tried doing this:我试过这样做:
d3.select("#myCircle0").click();
But it does not work.但它不起作用。 Is there an alternative way of firing D3 event for a specific element?是否有另一种方法可以为特定元素触发 D3 事件?
You have to dispatch the event:您必须调度事件:
d3.select("#myCircle0").dispatch("click");
Here is a demo with a slightly modified code, dispatching the click to the first circle:这是一个带有稍微修改的代码的演示,将点击发送到第一个圆圈:
const vis = {} vis.svg = d3.select("body").append("svg").attr("width", 500).attr("height", 500) vis.g = vis.svg.append("g") const circles = [20, 20, 20]; const myCircles = vis.g.selectAll('circle').data(circles).enter() myCircles.append('circle').attr('id', (d, i) => { return 'myCircle' + i }).attr('cx', (_, i) => 100 + 50 * i).attr('cy', 100).attr('r', (d, i) => d).attr('fill', 'gainsboro').attr('stroke', 'grey').on('click', function(event, d) { d3.select(this).attr('stroke', 'black') d3.select(this).attr('stroke-width', '2px') }); d3.select("#myCircle0").dispatch("click");
<script src="https://d3js.org/d3.v7.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.