如何在D3回调中访问当前选择? [英] How can I get access to the current selection inside a D3 callback?

查看:248
本文介绍了如何在D3回调中访问当前选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在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?

推荐答案

这里的问题是使用箭头函数来访问

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

应该是:

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

请参阅此处有关箭头f的文档关于的修改: 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

它说:


与函数表达式相比,箭头函数表达式的语法更短,并且词汇绑定了这个值(不绑定它自己的, 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元素,请使用第二个和第三个参数合并:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆