【问题标题】:D3 get attributes from elementD3 从元素中获取属性
【发布时间】:2017-09-24 14:05:30
【问题描述】:

我正在尝试一些基本的 d3,我一直在尝试使用 d3 获取每个 rect 的属性,但我无法获得任何东西。

当我尝试d3.selectAll("rect") 时,我得到了

我如何使用d3.selectAll("rect").select("part1").attr(...) 或类似的东西访问rect 的属性?我想访问所有rect 的不同属性。

【问题讨论】:

    标签: javascript d3.js svg


    【解决方案1】:

    您可以使用 getter 获取元素的任何属性:

    d3.select(foo).attr("bar")
    

    这基本上是只有一个参数的attr() 函数。

    这是一个演示。有两类矩形,part1part2。我正在选择所有 part1 矩形并获取它们的 x 位置:

    var svg = d3.select("svg");
    var rects = svg.selectAll(null)
      .data(d3.range(14))
      .enter()
      .append("rect")
      .attr("fill", "teal")
      .attr("y", 20)
      .attr("x", d => 10 + 12 * d)
      .attr("height", 40)
      .attr("width", 10)
      .attr("class", d => d % 2 === 0 ? "part1" : "part2");
    
    d3.selectAll(".part1").each(function(d,i) {
      console.log("The x position of the rect #" + i + " is " + d3.select(this).attr("x"))
    })
    <script src="https://d3js.org/d3.v4.min.js"></script>
    <svg></svg>

    【讨论】:

    • 谢谢,我对上面的代码还有两个问题。 1..attr("x", d =&gt; 10 + 12 * d) d =&gt; 10 + 12 * d 是什么意思? 2.d3.select(this).attr("x")this是不是因为function(d,i)而传入的元素?
    • this 是 DOM 元素,无论 di。这个数学只是在 SVG 中传播矩形(d 从 0 到 13)。
    • 如何将 x 值存储在数组中和/或将它们绑定回矩形以供将来使用?
    • 请将此作为一个新问题提出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 2017-05-28
    • 2016-11-17
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    相关资源
    最近更新 更多