这个问题在d3 v5上。
在创建子元素时,我试图将父元素的类附加到子元素上。
var data = [
[0,10,20],
[10,20,30],
[45,55,65]
];
var svg = d3.select("svg");
var rowHeight = 15;
// dummy domain
var xScale = d3.scaleLinear().range([0,100]).domain([0,100]);
var rows = svg.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", (d,i)=>`translate(0,${rowHeight*i})`)
.attr("class", (d,i)=>"r"+i)
;
rows.selectAll("g")
.data((d)=>d)
.enter()
.append("g")
.attr("transform", (d,i)=>`translate(${xScale(d)})`)
.attr("class", (d,i)=>"c"+i) // how to get class = r* here?
// tried d3.select(this.parentNode).attr("class") but doesn't work
;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width=500 height=100></svg>
我尝试了d3.select(this.parentNode).attr("class")
,但这引发了错误。
基本思想是将行和列类放入每个“ g”元素中,因此进一步的选择将更加容易。
谢谢!
答案 0 :(得分:1)
.attr("class", function(d,i) { return d3.select(this.parentNode).attr("class"); })
As described in a similar question, this.parentNode
gives you the <g>
domain tree element itself, but what you need is a D3-wrapped object that supports calls to D3-specific functions such as .attr
.
Also note that this
isn't defined as usual in the arrow shorthand format but points to the surrounding context, as described in MDN.