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

查看:101
本文介绍了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")时,我会得到

如何使用d3.selectAll("rect").select("part1").attr(...)之类的方法访问rect的属性?我想访问所有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("foo")
  .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天全站免登陆