Assign IDs to Individual Axis Text Elements

[亡魂溺海] 提交于 2019-12-21 06:36:13

问题


I'm using d3.axis() to create axis labels and tick marks that I'd like to refer to individually using d3.select("#axisTextIDValue") but I see no way to manipulate the id attribute of individual text elements in an axis. Does anyone know how to create ID values for the ticks or text elements of an axis?


回答1:


While the other answer does explain how to select the ticks, if you want to assign unique ids to generated elements like these, you can do so using subselections by giving an id or class to the g that you've called for your axis and then setting ids for the child text elements based on their array position:

 d3.select("svg").append("g").attr("id", "axisG").call(axis);
 d3.select("#axisG").selectAll("text").attr("id", function(d,i) {return "axisText" + i});

 d3.select("#axisText0").node(); //demonstrates selectability

That said, this probably isn't a very good idea and there are better ways to deal with ticks/labels/voronoi/etc that are generated on-the-fly by D3, but I wanted to make sure to put an answer up here just in case somebody is looking for how to do this kind of thing.




回答2:


The tricky part of this is that you will not know ahead of time what ticks you have or how many (unless you use tickValues property on your axis).

In general you can class the group you create your axis in and use that as a basis for further selections. For example

var axisGroup = parent.append('g')
                .attr('class', 'axis')

axisGroup.call(axis);

I believe the tick lines get assigned the "tick" class so you can select all the tick lines:

axisGroup.selectAll('.tick');

Or all the text labels:

axisGroup.selectAll('text');


来源:https://stackoverflow.com/questions/12825630/assign-ids-to-individual-axis-text-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!