【问题标题】:Firing D3 event for an element为元素触发 D3 事件
【发布时间】:2021-12-30 19:26:13
【问题描述】:

我已将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')
    })

有没有办法从元素外部触发这个click 事件?我试过这样做:

d3.select("#myCircle0").click();

但它不起作用。 是否有另一种方法可以为特定元素触发 D3 事件?

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    你必须派发事件:

    d3.select("#myCircle0").dispatch("click");
    

    这是一个代码稍作修改的演示,将点击发送到第一个圆圈:

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 2013-07-25
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多