D3 从元素获取属性 [英] D3 get attributes from element

查看:93
本文介绍了D3 从元素获取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试一些基本的 d3,我一直在尝试使用 d3 获取每个 rect 的属性,但我什么也得不到.

I am trying some basic d3 and i have been trying to get the attributes of each of the rect using d3 but I am not able to get anything.

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

When i try d3.selectAll("rect"), I get

如何通过使用类似 d3.selectAll("rect").select("part1").attr(...)<的东西来访问 rect 的属性/code> 或类似的东西?我想访问所有 rect 的不同属性.

How do can i access attributes of rect by using something like d3.selectAll("rect").select("part1").attr(...) or something similar? I want to access different attributes of all rect.

推荐答案

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

You can get any attribute of an element using a getter:

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

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

Which is basically the attr() function with just one argument.

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

Here is a demo. There are two classes of rectangles, part1 and part2. I'm selecting all part1 rectangles and getting their x positions:

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>

这篇关于D3 从元素获取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆