如何在 D3 回调中访问当前选择?
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 获取节点,但是如果我没有添加类?
最佳答案
这里的问题是使用箭头函数访问this
。
应该是:
.attr("y", function(d){
console.log(this);
return d;
})
请参阅此处有关this
的箭头函数的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
它说:
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
,请结合使用第二个和第三个参数:
.attr("y", (d, i, n) => {
console.log(n[i]);
return n[i];
})
关于javascript - 如何访问 D3 回调中的当前选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38624700/