繁体   English   中英

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

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

如何在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;
})

看到这里就左右箭头功能的文档thishttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

它说:

箭头函数表达式的语法比函数表达式短,并且按词法绑定此值(不绑定其自身的this,arguments,super或new.target)。

为了得到当前的DOM元素this箭头的功能,使用第二个和第三个参数组合:

.attr("y", (d, i, n) => {
    console.log(n[i]);
    return n[i];
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM