【问题标题】:.attr not defined d3js.attr 未定义 d3js
【发布时间】:2016-09-19 21:22:18
【问题描述】:

我有一个 svg,我希望在其中进行缩放和平移。 我遵循了这个例子:http://bl.ocks.org/sgruhier/1d692762f8328a2c9957 using d3.js v3

我在打字稿中如下实现:

            this._svg = d3.select('body')
                .append('svg')
                .attr('style', 'max-width: 100%')
                .attr('viewBox', this._viewbox_x + ' ' + this._viewbox_y + ' ' + this.responsemodel.width + ' ' + this.responsemodel.height)
                .call(d3.behavior.zoom().on('zoom', this.zoom))
                .append('g')

还有我的缩放功能

 zoom() {
    this._svg.attr('transform', 'translate(' + (<d3.ZoomEvent>d3.event).translate + ')scale(' + (<d3.ZoomEvent>d3.event).scale + ')');
}

运行时,我被告知“无法读取未定义的属性 'attr'”,这是因为 _svg 未定义。

有人可以向我解释这是为什么以及如何解决它吗?

提前致谢

【问题讨论】:

  • 有没有机会将完整的代码放在小提琴中? jsfiddle.net
  • 是的。 jsfiddle.net/a1L0jLj3但是这里没有出现问题
  • 你需要把你所有的 TypeScript 放在小提琴中。您可以通过选择当前显示“JavaScript”的设置 cog 并将其更改为 TypeScript 来更改代码输入文件上的语言

标签: d3.js svg


【解决方案1】:

我猜这是因为您的事件回调中的this 引用了window 对象。

您是否尝试将代表您的图表的this 绑定到事件函数:

    this._svg = d3.select('body')
        .append('svg')
        .attr('style', 'max-width: 100%')
        .attr('viewBox', this._viewbox_x + ' ' + this._viewbox_y + ' ' + this.responsemodel.width + ' ' + this.responsemodel.height)
        .call(d3.behavior.zoom().on('zoom', this.zoom.bind(this)))
        .append('g')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 2011-08-02
    • 2015-09-06
    • 1970-01-01
    相关资源
    最近更新 更多