【发布时间】:2023-03-25 07:30:02
【问题描述】:
我正在为我的 d3js 图表创建一个图例 (var legend)。数据绑定到父“g”元素,特别是我需要在子“文本”元素中获取的字符串(标签)。
问题:如何将 'g' 元素中的父 data 分配给子文本元素?
代码:
var legend = svg.selectAll(".legend")
.data(color.domain().slice().reverse()) // color is array of strings with length = 6
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(-20," + i * 20 + ")"; });
legend.data(headers).enter().append("text") // headers is array of strings with length = 6
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return this.parentElement.__data__; }); // not working code here
谢谢!完整代码:https://github.com/DeBraid/www.cacheflow.ca/blob/master/styles/js/d3kickchart.js
【问题讨论】:
-
These answers 可能会有所帮助。
-
一般情况下,调用
.select()会继承数据,即legend.select("text").//etc。
标签: javascript arrays dom d3.js