在http://bost.ocks.org/mike/selection/ , Mike 谈到在选择上应用函数。
When you use a function to define a selection.attr or selection.style, the function is called for each element; the main difference with grouping is that the second argument to your function (i) is the within-group index rather than the within-selection index.
这可能很简单,但出于某种原因,我不能完全理解这一点。任何人都可以用一个例子来解释这一点。
最佳答案
the main difference with grouping is that the second argument to your function (i) is the within-group index rather than the within-selection index.
还记得在 d3 中传递给任何 attr、style 等函数的索引吗?
...
.attr('something', function(d, index) {
// major gymnastics with d and index
}
因此,当您执行 selectAll 时,每个 组的索引从 0 开始。
因此,如果您执行两个 链式 selectAll,其中第一个(组)级别是行 (tr),第二个(子)级别是单元格 (td),您将传递以下内容作为 2 行 x 3 单元格表的索引
0, 1, 2, 0, 1, 2
代替
0, 1, 3, 4, 5, 6
当您使用单个 selectAll 选择仅 6 个节点时,这是您所期望的。
下面的代码片段说明了这一点
d3.selectAll("#a tr").selectAll("td").text(function(d, index) {
return index;
})
d3.selectAll("#b td").text(function(d, index) {
return index;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Grouped cells (i.e. 2 selectAll)
<table id="a">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Ungrouped cells (i.e. 1 selectAll)
<table id="b">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
您链接到的页面上的第一个动画 (http://bost.ocks.org/mike/selection/) 很好地说明了这一点 - 这是相同标记的版本
关于javascript - D3.js - 选择如何工作 - 需要对 Mike 的文章进行澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32013889/