在d3中获取元素的属性并不优雅

Getting the properties of an element in d3 is not elegant

本文关键字:属性 不优雅 元素 d3 获取      更新时间:2024-05-24

这是我的代码片段:

我试图了解如何使用d3获取DOM对象的属性。在这种情况下,在对象返回事件之后。例如,我将如何访问"x1"属性。

var svg = d3.select('svg')
  .append('polyline')
  .attr('x1', 20)
  .attr('y1', 100)
  .attr('x2', 100)
  .attr('y2', 100)
  .attr('points', "20,100 100,100 100,100 180,100")
  .attr('fill', 'none')
  .attr('stroke', palette.gray)
  .attr('marker-start', "url(#triangle)")
  .attr('marker-mid', "url(#triangle)")
  .attr('marker-end', "url(#triangle)")
  .on('click', function(){
        console.log('polyline click');
        console.log(this);            
  });

我使用

  1. console.log(this['x1']);--返回"未定义"
  2. console.log(this.attr('x1');--TypeError:this.attr不是函数
  3. console.log(this.property('attr');--TypeError:this.properties不是函数

我最终发现解决方案是使用:d3.select(this).attr("cx")

什么是"this"?如果我将"this"打印到控制台,我似乎会将DOM对象作为返回

<polyline x1="20" y1="100" x2="100" y2="100" points="20,100 100,100 100,100 180,100" fill="none" stroke="#708284" marker-start="url(#triangle)" marker-mid="url(#triangle)" marker-end="url(#triangle)">

不得不再次选择元素似乎有点"不明智"。我错过了一个技巧吗?

不,你没有错过任何东西。

this确实是您所记录的DOM元素,问题是attr()是D3函数,特别是在D3.selection上

您需要做的是将DOM元素转换为一个选择,这样您就可以利用d3-helper函数。这样做的方法就像你有一样

d3.select(this)