【问题标题】:Getting the properties of an element in d3 is not elegant在 d3 中获取元素的属性并不优雅
【发布时间】:2015-02-27 02:17:58
【问题描述】:

这是我的代码 sn-p:

我试图了解如何使用 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 is not a function
  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)">

不得不再次选择元素似乎有点'hacky'。我是不是漏了个小把戏?

【问题讨论】:

  • 你没有错过任何东西。 .attr 是一个 d3 选择的方法,所以你当然必须再次选择。这是一个 JavaScript 约定,this 应该是事件发生的元素。例如,JQuery 遵循相同的模型。如果你不想选择直接做javascript way:this.getAttribute('x1');
  • WOAHH 我使用了 getAttribute(),我认为我的大脑爆炸了(它起作用了)。那么“this”是对 DOM 元素的标准化引用,因此也可以通过 javascript 和 JQUERY 访问?
  • 是的,this 这是一个标准的DOM element。然后,您可以使用 d3.select(this) 将其转换为 d3 选择,或者如果需要,使用 $(this) 将其转换为 jQuery 对象,或者根据需要使用它。
  • 您可能还会发现d3.select(this) 等同于您目前拥有的svg。您将.append 的结果分配给svg,这将是折线。
  • Imran - 如果我的回答对您有所帮助,您愿意接受吗?如果没有,您还需要更多详细信息吗?

标签: javascript svg d3.js


【解决方案1】:

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

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

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

d3.select(this)

【讨论】:

    猜你喜欢
    • 2017-09-24
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多