我正在使用“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
控制台结果
我不知道这是怎么回事。
最佳答案
当您向诸如 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/