获取多个元素的属性值 [英] Getting attribute values of multiple elements

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

问题描述

我想获取选择中多个元素的属性值作为数组,但是我找不到一种简洁的方法.

I want to get attribute values of the multiple elements in a selection as an array, but I cannot find a concise way.

例如,在svg元素中,有一些circle,您需要获取所有这些元素的cx属性.

For example, in a svg element, there are some circles and you need to get cx attribute of the all of them.

我尝试过:

var cxs = d3.select("svg")
    .selectAll("circle")
    .attr("cx");

但是结果只是一个圆的值(例如"523.4777243042896"),我需要全部cx. 圆的坐标是使用复杂的仿真算法计算的,因此无法使用原始数据来获得它们. 有什么好的方法可以获取所有值?

But the result is only a value (say "523.4777243042896") of one circle, and I need all cxs. The coordinates of the circles are calculated with a complicated simulation algorithm, so it is impossible to get them using the original data. Is there any good way to get all values?

谢谢.

推荐答案

如果我正确理解,则希望获取cx值的列表.因此,这是您可以做到这一点的一种方法.

If I'm understanding correctly, you want to get a list of the cx values. So, here's one way you could do that.

var cxs = [];
d3.selectAll("circle")[0].forEach(function(circle) {
  cxs.push(circle.getAttribute('cx'));
});

要使其更短一些,可以使用map()

To make it a little shorter you could use map()

var cxs = d3.selectAll("circle")[0].map(function(circle) {
  return circle.getAttribute('cx');
});

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

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