javascript - 在 d3.selectAll 中使用 attr 方法时出现“未定义”

标签 javascript d3.js

我正在使用“d3-select”包来更改我的绘图,但我被这个奇怪的错误阻止了。

当我在 selectAll('path') 之后使用 'attr' 方法时,它工作得很好,但当我在 selectAll('line') 上使用它时,它就中断了。我发现 selectAll('line') 上的 'attr' 没有收到任何信息。

代码

const paths = this.$gPlot.selectAll('path');
console.log('paths =', paths);
paths.attr('d', path => console.log(path)); // there's two path elements

const lines = this.$gPlot.selectAll('line');
console.log('lines =', lines);
lines.attr('y1', line => console.log(line)); // there's three line elements

控制台结果

image

我不知道这是怎么回事。

最佳答案

当您向诸如 attr() 之类的函数提供函数时,函数的第一个参数是绑定(bind)到元素的数据,该数据通常是之前通过调用 data 分配的() 在组上。它不是 SVG 元素本身。

在您的情况下,数据绑定(bind)到路径,但没有绑定(bind)到行,因此在调用函数时,您会在行上得到 undefined 。要通过函数获取对 SVG 元素的引用,请使用:

lines.each(function() {
    console.log(this);
})

您必须使用完整的函数,而不是简写,才能正确确定 this 的作用域

关于javascript - 在 d3.selectAll 中使用 attr 方法时出现“未定义”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48081472/

相关文章:

javascript - 如何获取XML子节点的长度

javascript - 如何给id赋值?

javascript - 如何在 d3.scale.ordinal() 中指定域?

javascript - 如何使用 d3.js 为嵌入条形图中的折线图设置不同的范围

javascript - D3 带标签的箭头链接

javascript - 在 Angular 的 ng 属性上使用属性选择器进行样式设置

javascript - 无法在处理程序中获取 Dojo 文本框值

javascript - 随机图片,随机文本刷新后显示

javascript - 仪表 D3,显示值位置

javascript - 在 D3 中设计图例