How can I get access to the current selection inside a D3 callback?

后端 未结 1 1681
长发绾君心
长发绾君心 2020-12-04 00:39

How can I get access to the current selection inside a D3 callback?

group.selectAll(\'.text\')
    .data(data)
    .enter()
    .append(\'text\')
    .text((         


        
相关标签:
1条回答
  • 2020-12-04 00:54

    The problem here is the use of an arrow function to access this.

    It should be:

    .attr("y", function(d){
        console.log(this);
        return d;
    })
    

    See here the documentation about arrow functions regarding this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

    It says:

    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).

    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];
    })
    
    0 讨论(0)
提交回复
热议问题