出于某种原因,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/