javascript - 如何使用带有 ES6 箭头符号的 d3 的每个方法

标签 javascript d3.js

出于某种原因,d3 使用 this 来引用 .each() 迭代中的当前元素。

我有这段代码:

var me = this;
...
d3.selectAll(".region").each(function(d) {
    d3.select(this).style("fill", me.compute_color(...));
})

在 ES6 中,我可以使用箭头符号来避免覆盖 this:

d3.selectAll(".region").each(d => {
    d3.select(this).style("fill", this.compute_color(...));
})

但是,这段代码不起作用,因为 d3 选择了错误的元素。事实上,我已经失去了对该元素的唯一引用,因为 this 没有被 d3 覆盖。

如何更改 d3.select(this) 使其正常工作?

最佳答案

您可以使用作为第二个参数传递的索引来访问集合中的正确元素:

let selection = d3.selectAll(".region");
selection.each((d, i) => {
    d3.select(selection[0][i]).style("fill", this.compute_color(...));
})

关于javascript - 如何使用带有 ES6 箭头符号的 d3 的每个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33771186/

相关文章:

javascript - 将 onkeydown 收集的击键转换为 JavaScript 中的字符

javascript - Promise 的极其简单的实现是如何工作的

d3.js - 如何在 Angular 2 中实现 D3

javascript - 使用文本框进行交叉过滤

javascript - 通过 Typeahead 将 Id 值绑定(bind)到隐藏的输入

javascript - 如何为 props 设置默认值

javascript - foursquare api 中的最大结果数?

javascript - Y 轴已创建但不可见

javascript - D3.js 条形图根据数据的权重或值生成条形颜色

javascript - 在 D3 中的条形图上叠加一个函数