如何访问 D3 回调中的当前选择? [英] How can I get access to the current selection inside a D3 callback?
问题描述
如何在 D3 回调中访问当前选择?
How can I get access to the current selection inside a D3 callback?
group.selectAll('.text')
.data(data)
.enter()
.append('text')
.text((d) => d)
.attr('class', 'tick')
.attr('y', (d) => {
// console.log(this) <-- this gives me window :( but I want the current selection or node: <text>
return d
})
我可以在回调中做一个 d3.select('.tick')
,因为那时我已经添加了一个类并且可以通过 d3.select 获取节点,但是如果我没有添加课程?
I could do a d3.select('.tick')
in the callback, since by then I've added a class and can get the node via d3.select, but what if I didn't add the class?
推荐答案
这里的问题是使用箭头函数来访问this
.
The problem here is the use of an arrow function to access this
.
应该是:
.attr("y", function(d){
console.log(this);
return d;
})
在此处查看有关 this
的箭头函数的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
See here the documentation about arrow functions regarding this
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
它说:
与函数表达式相比,箭头函数表达式的语法更短,并且在词法上绑定了 this 值(不绑定自己的 this、arguments、super 或 new.target).
An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target).
要在箭头函数中获取当前 DOM 元素 this
,请结合使用第二个和第三个参数:
To get the current DOM element this
in an arrow function, use the second and third arguments combined:
.attr("y", (d, i, n) => {
console.log(n[i]);
return n[i];
})
这篇关于如何访问 D3 回调中的当前选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!