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

Getting the properties of an element in d3 is not elegant

这是我的代码片段:

我试图了解如何使用 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(这个['x1']); -- returns 'undefined'
  2. console.log(this.attr('x1'); -- TypeError: this.attr 不是函数
  3. console.log(this.property('attr'); -- TypeError: this.property 不是函数

我终于找到解决方案是使用:d3.select(this).attr("cx")

什么是“这个”?如果我将 '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)">

似乎有点'hacky'必须再次select该元素。我是不是漏掉了什么技巧?

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

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

您需要做的是将 DOM 元素转换为一个选择,以便您可以利用 d3 辅助函数。这样做的方法和你一样

d3.select(this)