该selection.data函数的描述包括具有多个组(链接)的示例,其中二维数组被转换为HTML表.
在d3.js v3中,对于较低维度,访问器函数包括第三个参数,该参数是父组的数据的索引:
td.text(function(d,i,j) {
return "Row: " + j;
});
Run Code Online (Sandbox Code Playgroud)
在v4中,该j参数已被选择的NodeList取代.如何立即访问父组的基准索引?
Ger*_*ado 16
好吧,有时答案不提供解决方案,因为解决方案可能不存在.这似乎是这种情况.
根据博斯托克的说法:
我已将新的双层选择实现合并到master中,并简化了如何使用并行父阵列跟踪父项.
这种新方法的一个很好的特性是selection.data可以用与其他选择函数完全相同的方式计算值函数:values函数被传递{d,i,nodes},其中这是父节点,d是父节点datum,i是父(组)索引,nodes是父节点的数组(每个组一个).此外,parent数组可以通过不重新组合选择的子选项重用,例如selection.select,因为parents数组是不可变的.
这种变化限制了功能 - 在某种意义上你不能 从选择函数,父数据和组索引中访问父节点- 但我相信这最终是一件好事,因为它鼓励更简单的代码.
(强调我的)
这是链接:https://github.com/d3/d3-selection/issues/47
因此,不可能使用selection父组的索引(父组的索引可以使用selection.data,如下面的代码片段所示).
var testData = [
[
{x: 1, y: 40},
{x: 2, y: 43},
{x: 3, y: 12},
{x: 6, y: 23}
], [
{x: 1, y: 12},
{x: 4, y: 18},
{x: 5, y: 73},
{x: 6, y: 27}
], [
{x: 1, y: 60},
{x: 2, y: 49},
{x: 3, y: 16},
{x: 6, y: 20}
]
];
var svg = d3.select("body")
.append("svg")
.attr("width", 300)
.attr("height", 300);
var g = svg.selectAll(".groups")
.data(testData)
.enter()
.append("g");
var rects = g.selectAll("rect")
.data(function(d, i , j) { console.log("Data: " + JSON.stringify(d), "\nIndex: " + JSON.stringify(i), "\nNode: " + JSON.stringify(j)); return d})
.enter()
.append("rect");Run Code Online (Sandbox Code Playgroud)
<script src="https://d3js.org/d3.v4.min.js"></script>Run Code Online (Sandbox Code Playgroud)
我的解决方法是有点类似的Dinesh拉詹的,假设需要对属性的父索引someAttr的g.nestedElt:
v3:
svg.selectAll(".someClass")
.data(nestedData)
.enter()
.append("g")
.attr("class", "someClass")
.selectAll(".nestedElt")
.data(Object)
.enter()
.append("g")
.attr("class", "nestedElt")
.attr("someAttr", function(d, i, j) {
});
Run Code Online (Sandbox Code Playgroud)
第4节:
svg.selectAll(".someClass")
.data(nestedData)
.enter()
.append("g")
.attr("class", "someClass")
.attr("data-index", function(d, i) { return i; }) // make parent index available from DOM
.selectAll(".nestedElt")
.data(Object)
.enter()
.append("g")
.attr("class", "nestedElt")
.attr("someAttr", function(d, i) {
var j = +this.parentNode.getAttribute("data-index");
});
Run Code Online (Sandbox Code Playgroud)