Get attributes of existing SVG elements and bind a

2019-07-09 21:48发布

I have an existing svg element such as:

<svg width="300" height="200">
    <circle cx="50" cy="10" r="5" fill="green"></circle>
    <circle cx="100" cy="20" r="10" fill="green"></circle>
    <circle cx="150" cy="30" r="15" fill="green"></circle>
</svg>

I would like to extract the cx values of the circles and bind them as data back to the circles. I can do it with one:

var x = +d3.select('circle').attr('cx');
d3.select('circle').datum(x);

However I cannot figure out how to collect all of the cx values into an array and them join them to the circles. (Or perhaps there a more direct way to do this without the data array.)

This answer explains how to view all attributes in the console, but doesn't explain how to store them or bind them to DOM elements.

1条回答
Lonely孤独者°
2楼-- · 2019-07-09 22:36

Does this work for you?

d3.selectAll('circle').datum(function() {
  return parseFloat(this.getAttribute('cx'));
});
查看更多
登录 后发表回答