且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何访问 D3 回调中的当前选择?

更新时间:2023-08-30 20:51:52

这里的问题是使用箭头函数来访问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];
})