2 回答
![?](http://img1.sycdn.imooc.com/533e4d660001312002000200-100-100.jpg)
TA贡献1820条经验 获得超9个赞
访问您的行的正确方法是函数内的 d3.select(this) 。d 参数是连接的数据。我不知道是否有更好的迭代方法,但 .each 函数对我有用。
以下是https://www.d3indepth.com/selections/中 .each 的示例用法:
function addNumberedCircle(d, i) {
d3.select(this)
.append('circle')
.attr('r', 40);
d3.select(this)
.append('text')
.text(i + 1)
.attr('y', 50)
.attr('x', 30);
}
d3.selectAll('g.item')
.each(addNumberedCircle);
![?](http://img1.sycdn.imooc.com/5333a1bc00014e8302000200-100-100.jpg)
TA贡献1876条经验 获得超7个赞
文档说 .each 函数的三个参数是 (1) 数据,(2) 当前索引,以及 (3) 选择中的节点。https://github.com/d3/d3-selection/blob/v1.4.1/README.md#selection_each
在这里提供一个答案,以防万一有人想使用 ES6 箭头函数,或者他们在使用已接受答案中使用的“this”关键字时遇到问题。
在每个函数中选择元素时使用“this”很好,但我在 SPA 应用程序中使用“this”时遇到了问题,其中“this”通常意味着其他含义,可能会让人感到困惑。
为避免使用“this”,可以将代码更改为:
d3.select('svgEditor').selectAll('line').each(function(d,i){
d3.select(this).append.....
});
到:
d3.select('svgEditor').selectAll('line').each((data, i, nodes) => {
d3.select(nodes[i]).append....
});
这篇文章有助于解释https://medium.com/@yonester/on-d3-and-arrow-functions-b6559c1cebb8
添加回答
举报