【问题标题】:Why isn' t this selecting and changing the attributes in D3?为什么不选择和更改 D3 中的属性?
【发布时间】:2021-08-03 10:55:06
【问题描述】:

我有一个名为 data 的简单数据对象,其中包含一些我希望用于我的圆圈的半径、坐标和颜色。但是我现在想让它们全部变成橙色,但最后一行代码似乎没有运行?

const myCircles = svg.selectAll()
.data(data);

myCircles.enter().append('circle')
    .attr('cx' , (d) => d.x)
    .attr('cy' , (d) => d.y)
    .attr('r' , (d) => d.radius )
    .attr('fill' , (d) => d.color )

myCircles.attr('fill' , 'orange');

我尝试过的其他方法无效

我试过了

d3.selectAll(myCircles).attr('fill' , 'orange');

我试过了

svg.selectAll(myCircles).attr('fill' , 'orange');

但两次都收到错误:d3.v7.min.js:2 Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Element': '[object Object]' is not a valid selector.

什么有效,但我不想要它

d3.selectAll('circle').attr('fill' , 'orange')

因为我想通过变量 myCircles 选择圆圈,而不是使用 d3 标签“circle”,因为我打算稍后制作更多圆圈。

【问题讨论】:

  • myCircles 包含空的 update 选择,而您正在附加到 enter 选择。要操作输入选择中的圆圈,您需要存储对该选择的引用,或者您需要使用.merge() 来合并两个选择。

标签: javascript svg d3.js


【解决方案1】:

myCircles 变量为空,因为它只是更新选择,而不是附加圆圈的输入选择。如果您需要一个变量来保存附加的圆圈,您可以将输入选择分配给它:


const myCircles = svg.selectAll()
.data(data);

const myOrangeCircles = myCircles.enter().append('circle')
    .attr('cx' , (d) => d.x)
    .attr('cy' , (d) => d.y)
    .attr('r' , (d) => d.radius )
    .attr('fill' , (d) => d.color )

myOrangeCircles.attr('fill' , 'orange');

我推荐的一个很好的资源是官方General Update Pattern Tutorial


补充:

除了变量之外,您还可以使用类来区分对象。例如,如果您将圈子附加到一个类中,您可以稍后使用selectAll 来仅检索与该类匹配的圈子:

myCircles.enter().append('circle')
    .attr('cx' , (d) => d.x)
    .attr('cy' , (d) => d.y)
    .attr('r' , (d) => d.radius )
    .attr('fill' , (d) => d.color )
    .classed('myOrangeCircle', true)

svg.selectAll('circle.myOrangeCircle').attr('fill' , 'orange');

【讨论】:

  • 非常感谢罗德里戈!从现在开始,我将使用您一直展示的第一种方法!我也喜欢使用类,只需为此编写 .attr('class' , 'classname') ,但可能需要添加一个 .attr('class' ,'classname') 。使用它时在字符串之前:)
猜你喜欢
  • 1970-01-01
  • 2012-07-15
  • 2013-09-24
  • 2013-06-20
  • 2013-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多