javascript - D3.js - 选择如何工作 - 需要对 Mike 的文章进行澄清

标签 javascript d3.js

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/) 很好地说明了这一点 - 这是相同标记的版本

enter image description here

关于javascript - D3.js - 选择如何工作 - 需要对 Mike 的文章进行澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32013889/

相关文章:

&lt;script&gt; block 中的 ASP.NET 服务器端注释

javascript - 二元函数等价 - demethodize

javascript - HTML 页面上的数据库搜索功能可能吗?

javascript - 将 HTML/JS 转换为 React,其中首先加载 JS 并需要 HTML 元素

javascript - 如何在 D3 Sankey 图中突出显示整个路径?

javascript - D3.js - 力图。如何添加缩放和平移

javascript - 下拉菜单上的 jquery 超时(悬停意图)

javascript - 如何通过点击d3.js图调用ajax

javascript - 将子组中的名称排序为组 - 重组 json 数据

javascript - 将 Twitter Bootstrap 弹出窗口与 D3.js 集成