javascript – D3.js – 如何选择工作 – 需要澄清Mike的文章

http://bost.ocks.org/mike/selection/,迈克谈到在选择上应用函数.

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开始.

因此,如果您执行两个链式selectAlls,其中第一个(组)级别是行(tr),第二个(子级)级别是单元格(td),则您将传入以下作为2行x 3单元格的索引表

0,1,2,2

代替

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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...