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

tim*_*dit 2 javascript svg d3.js

这是我的代码片段:

我试图了解如何使用 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);            
  });
Run Code Online (Sandbox Code Playgroud)

我用了

  1. console.log(this['x1']); -- 返回“未定义”
  2. console.log(this.attr('x1'); -- TypeError: this.attr 不是函数
  3. console.log(this.property('attr'); -- TypeError: this.property is not a function

我终于发现解决方案是使用: 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)">
Run Code Online (Sandbox Code Playgroud)

不得不再次选择元素似乎有点“hacky”。我在这里错过了一个技巧吗?

Ian*_*Ian 5

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

this确实是您登录时的 DOM 元素,问题在于它attr()是一个 D3 函数,特别是在 d3.selection 上。

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

d3.select(this)